1

我一定在这里做错了什么: 文本视图与

我的 Cocoa 应用程序有一个围绕自定义视图的滚动视图,而该自定义视图又具有一个文本视图。我只希望看到一个“这是一个”字符串,但角落里还有一个额外的字符串。我已将代码减少到非常少的程度,但仍然不明白我的错误是什么,所以我在这里寻找线索。

自定义视图的视图控制器如下,但为简单起见,这里是项目的链接。

#import "TTTSimpleCtrlView.h"

@interface TTTSimpleCtrlView ()

@property (strong,nonatomic) NSTextView *tv1;
@property (strong,nonatomic) NSTextStorage *ts;

@end

@implementation TTTSimpleCtrlView

- (void) awakeFromNib {
    NSFont *font = [NSFont fontWithName:@"Courier New Bold" size:20.0f];
    NSMutableParagraphStyle *styleModel = [[NSParagraphStyle  defaultParagraphStyle] mutableCopy];
    [styleModel setLineHeightMultiple:1.0];
    //    [styleModel setLineSpacing:fontRect.size.height * 2];
    NSDictionary *textAttrs = [NSDictionary dictionaryWithObjectsAndKeys: font, NSFontAttributeName,
                                     [NSColor blackColor] ,NSForegroundColorAttributeName,
                                     [NSColor whiteColor], NSBackgroundColorAttributeName,
                                     styleModel, NSParagraphStyleAttributeName,
                                     nil];
    NSString *pilcrowStr = @"This is a test.";
    NSAttributedString *s = [[NSAttributedString alloc] initWithString:pilcrowStr attributes:textAttrs];
    NSRect rect = [s boundingRectWithSize:NSMakeSize(INFINITY,INFINITY)options:0];
    NSLayoutManager *lm = [[NSLayoutManager alloc] init];
    NSTextContainer *tc = [NSTextContainer new];

    [tc setContainerSize:s.size];
    [lm addTextContainer:tc];

    _ts = [[NSTextStorage alloc] init];
    [_ts setAttributedString:s];

    [_ts addLayoutManager:lm];
    [lm replaceTextStorage:_ts];

    rect.origin.x = 10;
    rect.origin.y = rect.size.height;
    NSTextView *v = [[NSTextView alloc] initWithFrame:rect textContainer:tc];
    [v setDrawsBackground:YES];
    [self addSubview:v];
}

- (BOOL) isFlipped {
    return YES;
}

- (void)drawRect:(NSRect)rect
{
    NSLog(@"drawRect & %lu subviews",self.subviews.count);
    for (NSTextView *v in self.subviews) {
        if(CGRectIntersectsRect(v.frame, rect) || CGRectContainsRect(rect, v.frame)) {
            [v drawRect:rect];
            NSLog(@"frame = %@",NSStringFromRect(v.frame));
        }
    }
    [super drawRect:rect];
}
4

1 回答 1

1

您正在调用:

[super drawRect:rect];

并且您正在自己的绘图功能中绘制文本。实际上,您正在绘制文本,而可可也在为您绘制文本。所以不要叫超级。

于 2014-02-13T11:30:13.593 回答