UITextView自适应高度

来源:互联网 发布:yes淘宝刷信用 编辑:程序博客网 时间:2024/05/17 06:25

   之前textView算文字高度总是拿不到合适的高度。在Stack Overflow 找到了解决方法备注在此。

代码如下:

 UITextView * textView=[[UITextView alloc] initWithFrame:CGRectMake(20, 40, self.view.frame.size.width-40, 20)];    textView.text=@"   I'm porting one of apps from iOS 6.1 to iOS 7. I'm using a layout where there's a UITextView that has a fix width, but it's height is based on its contentsize. For iOS 6.1 checking the contentsize.height and setting it as the textview's frame height was enough, but it doesn't work on iOS 7.\n  How can i then create a UITextView with a fixed width, but dynamic height based on the text it's showing? \n";    textView.textColor=[UIColor brownColor];    textView.font=[UIFont systemFontOfSize:14.0];    textView.layer.borderColor=[[UIColor lightGrayColor] CGColor];    textView.layer.borderWidth=1.0f;    [self.view addSubview:textView];            CGFloat fixedWidth = textView.frame.size.width;    CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];    CGRect newFrame = textView.frame;    newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);    textView.frame = newFrame;
下面是这个demo:


0 0
原创粉丝点击