我有一个UITextView,我想根据其内容动态调整大小。
由于某种原因,textview总是比其内容更短!这是代码:
_textView.text = [NSString stringWithFormat:@"Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test "];
CGRect frame = _textView.frame;
frame.size.height = _textView.contentSize.height;
_textView.frame = frame;
结果如下:
正如您所看到的,UITextView(白色)太短。如果我把更多或更少的内容放在那里,那么短缺是相同的,即
我确定它很简单,但我无法解决。
答案 0 :(得分:0)
在调整其框架大小之前,将UITextView添加到主视图(addSubview) (见this question)
答案 1 :(得分:0)
我在这里找到答案:https://stackoverflow.com/a/2487402/255463,然后我这样做:
首先,我使用故事板添加UITextView,然后使用故事板将textView嵌入到UIScrollView中,然后将每个视图与故事板的插座连接起来。在视图控制器子类中,这是我得到的:
#import "DetailViewController.h"
@interface DetailViewController ()
@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@end
@implementation DetailViewController
@synthesize textView = _textView;
@synthesize scrollView = _scrollView;
- (void)viewDidLoad
{
[super viewDidLoad];
self.textView.text = [NSString stringWithFormat:@"Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test "];
CGRect frame = self.textView.frame;
frame.size.height = self.textView.contentSize.height;
self.textView.frame = frame;
self.scrollView.contentSize = CGSizeMake(320.0, self.descriptionView.contentSize.height + 147.0);
}
@end
答案 2 :(得分:0)
我在iOS7中使用故事板时遇到了同样的问题。
我的解决方案是添加此代码:
CGRect newTextViewFrame = self.textView.frame;
newTextViewFrame.size.width = self.textView.contentSize.width + self.textView.contentInset.right + self.textView.contentInset.left;
newTextViewFrame.size.height = self.textView.contentSize.height + self.textView.contentInset.top + self.textView.contentInset.bottom;
self.textView.frame = newTextViewFrame;
在viewDidAppear:
视图生命周期方法中,它的大小立即适合它的内容。不幸的是,这个调整大小发生在视图已经出现之后,意味着用户看到它正在发生。
示例:
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
CGRect newTextViewFrame = self.textView.frame;
newTextViewFrame.size.width = self.textView.contentSize.width + self.textView.contentInset.right + self.textView.contentInset.left;
newTextViewFrame.size.height = self.textView.contentSize.height + self.textView.contentInset.top + self.textView.contentInset.bottom;
self.textView.frame = newTextViewFrame;
}