2015-10-19 93 views
0

我在UIView中添加了UITextViewUIView有一些高度取决于屏幕尺寸。 UITextView可以有更多或更少的文字。所以我想让UITextView的高度动态化,所以如果文字多了,它应该有更多的高度,但它应该小于主视图的高度。如果文字少,那么它的高度应该较小。ios中textview的动态高度?

+0

你不想让textview滚动吗? –

+0

不,我不想滚动 – Techiee

+0

使用故事板? –

回答

5

大小尝试一个UITextView它的内容编程:

UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)]; 
    [textView setDelegate:self]; 
    [textView setText:@"your long text"]; 
    [textView setScrollEnabled:NO]; 
    [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; 
-1

与此

-(void)dynamicTextSize{ 
UITextView *textView = [[UITextView alloc]initWithFrame:CGRectMake(200, 300, 200, 30)]; 
textView.center = self.view.center; 
[self.view addSubview:textView]; 

NSString *string = @"This is pour text.a hjajksdkja kajhdsjk akjdhs jakhd skjahs ajkdhsjkad hskja akjdhs ajkhdjskar"; 
textView.text = string; 

//UIFont *font = [UIFont fontWithName:@"Arial" size:16.0f]; 
NSDictionary *attrDict = [NSDictionary dictionaryWithObjectsAndKeys:textView.font, NSFontAttributeName, nil]; 

textView.backgroundColor = [UIColor lightGrayColor]; 

CGRect frame = [textView.text boundingRectWithSize:CGSizeMake(textView.frame.size.width, 10000) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin attributes:attrDict context:nil]; 

CGRect mFrame = textView.frame; 
mFrame.size.width = frame.size.width; 
mFrame.size.height = frame.size.height; 
textView.frame = mFrame; 

//NSLog(@"frame2:%@",NSStringFromCGRect(textView.frame)); 
} 
+0

什么是** attrdict **? – Techiee

+0

如何处理** size **。在哪里设置? – Techiee

+0

如何设置大小? – Techiee

0

如果使用textview与滚动禁用显示文本的多线,它只不过是一个UILabel更。我建议你为此目的使用UILabel

在情节串连图板,设置的约束如下:

enter image description here

并设置换行符作为自动换: enter image description here

+0

请注意约束值是根据我的需要给出。您可以根据您的需要修改它们 –

+0

用于文本环绕图像我使用textview作为标签 – Techiee

+0

您甚至可以将文本包装在uilabel中,唯一的区别是标签是只读的而文本视图是可编辑的。 –

0

同第一个答案,但在夫特4:

let screenSize = UIScreen.main.bounds 
let textView = UITextView.init(frame: CGRect(x: 1, y: 40, width: screenSize.width, height: screenSize.height)) 
textView.delegate = self as? UITextViewDelegate 
textView.isScrollEnabled = false 
view.addSubview(textView) 

let fixedWidth = textView.frame.size.width 
let newSize: CGSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat(MAXFLOAT))) 
var newFrame = textView.frame 
newFrame.size = CGSize(width: CGFloat(fmaxf(Float(newSize.width), Float(fixedWidth))), height: newSize.height)