Ios 子类uitextview并使用属性字符串计算大小
我正在对UITextView进行子类化,并尝试在计算单元格的大小之前计算它的大小,以便正确设置单元格高度。我试图使用BoundingRectize,但不幸的是,它没有返回预期的结果。见下文: 我在iOS 8上Ios 子类uitextview并使用属性字符串计算大小,ios,objective-c,Ios,Objective C,我正在对UITextView进行子类化,并尝试在计算单元格的大小之前计算它的大小,以便正确设置单元格高度。我试图使用BoundingRectize,但不幸的是,它没有返回预期的结果。见下文: 我在iOS 8上 @interface SCTextView : UITextView @end -(void)setText:(NSString *)text { [super setText:text]; self.attributedText = [[NSAttributedString
@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"]);
}
仅供参考-调用return后不会执行任何代码。是的,这只是为了说明每行的结果。我认为这是因为UITextView有一个默认的uiedgeinset{8,0,8,0}。