ios中textview的动态高度?

时间:2015-10-19 12:50:11

标签: objective-c cocoa-touch

我在UITextView内添加了UIViewUIView根据屏幕尺寸有一定的高度。 UITextView可以包含更多或更少的文字。所以我想让UITextView的高度为动态,所以如果文本更多,那么它应该有更多的高度,但它应该小于主视图的高度。如果文字少于那么它的高度应该更少。

4 个答案:

答案 0 :(得分:6)

以编程方式将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 :(得分:0)

如果您使用textview来显示禁用滚动的多行文字,那只不过是UILabel。我建议您将UILabel用于此目的。

在故事板中,按如下方式设置约束:

enter image description here

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

答案 2 :(得分:0)

与第一个答案相同,但在Swift 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)

答案 3 :(得分:-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));
}