sizeWithFont:constrainedToSize:lineBreakMode:和contentSize(Objective-C中的文本高度)之间的确定关系

时间:2011-08-10 11:16:33

标签: objective-c ios nsstring

// textView is type of UITextView

self.textView.text = @"Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.";

CGSize maxSize = {self.textView.contentSize.width, CGFLOAT_MAX};
CGSize computedSize = [self.textView.text sizeWithFont:self.textView.font
                                     constrainedToSize:maxSize
                                         lineBreakMode:UILineBreakModeWordWrap];

NSLog(@"Computed size - width:%f height:%f\nContent size - width:%f height:%f", computedSize.width, computedSize.height, self.textView.contentSize.width, self.textView.contentSize.height);

控制台输出:

  

计算尺寸 - 宽度:320.000000高度:450.000000

     

内容大小 - 宽度:320.000000高度:484.000000

为什么这些价值不相等?至少是高度。

1 个答案:

答案 0 :(得分:0)

文本视图的.bounds.size是什么?如果所有文本都适合文本视图,则内容大小仍可以报告为完整大小的视图。

UITextView是使用内部网络视图实现的,具有一些私人魔法。除了显示和编辑文本之外,用文本视图信任文本视图通常不是一个好主意。内部测量和计算已经并将继续在操作系统更新之间发生变化。

如果你想要的是改变UITextView的大小以适合所有文本,那么必须让文本视图本身进行此计算。例如:

CGRect frame = textView.frame;
frame.size.height = [textView sizeThatFits:CGSizeMake(frame.size.width, CGFLOAT_MAX)];
textView.frame = frame;