子类uitextview并使用属性字符串计算大小

时间:2014-12-10 01:31:24

标签: ios objective-c

我正在对UITextView进行子类化并尝试在手前(对于单元格)计算它的大小,以便我可以正确设置单元格高度。我正在尝试使用boundingRectWithSize,但不幸的是它没有返回预期的结果。见下文:

(我在iOS 8上)

@interface SCTextView : UITextView
@end

-(void)setText:(NSString *)text {
  [super setText:text];

  self.attributedText = [[NSAttributedString alloc] initWithString:self.text attributes:[SCColorScheme defaultScheme].defaultTextAttributes];
}

+(CGSize)measureWithAttributedString:(NSAttributedString *)attrString andWidthConstraint:(CGFloat)maxWidth {
    SCTextView *hello = [[self alloc] init];
    hello.text = attrString.string;
    CGRect f = hello.frame;
    f.size.width = maxWidth;
    hello.frame = f;
    [hello sizeToFit];

    // hello.frame.size.height returns 34.00
    return hello.frame.size;

    NSLog(@"are they the same?: %@", [hello.attributedText isEqualToAttributedString:attrString] ? @"YES" : @"NO");
    // Returns true

    // boundingRect.size.height returns 17.234
    CGSize boundRectSize =  [attrString boundingRectWithSize:CGSizeMake(maxWidth, CGFLOAT_MAX)
                                           context:nil
                                           ].size;

    // Returns false.
    NSLog(@"these are not: %@", [boundingRectSize.width isEqual:hello.frame.size.width] ? @"YES" : @"NO"]);
}

0 个答案:

没有答案