【问题标题】:Dynamically set the height of uitextview like message app像消息应用一样动态设置uitextview的高度
【发布时间】:2015-08-18 21:38:31
【问题描述】:

我在设置UITextView 的高度时遇到问题,例如消息应用程序。它是通过在出现换行时增加它的高度来实现的。

我的问题是,当用户编辑文本内容时,它并没有降低容器的高度,其中textview 是一个孩子。

我正在使用自动布局和这段代码

- (void)textViewDidChange:(UITextView *)textView {

    UITextPosition* pos = self.posttextView.endOfDocument;//explore others like beginningOfDocument if you want to customize the behaviour
    CGRect currentRect = [self.posttextView caretRectForPosition:pos];

    if (currentRect.origin.y > previousRect.origin.y){    
        if (self.containerHeightt.constant == 99) {        
            return;
        }

        self.containerHeightt.constant += 10;

        NSLog(@"the container height is %f",self.containerHeightt.constant);   
    }

    previousRect = currentRect;
}

请告诉我如何检测何时从textview 中删除了一行,然后降低容器的高度。

【问题讨论】:

  • 你试过只使用文本视图的contentSize 吗?
  • 不,我没有那样尝试。
  • 我可以在出现新行时增加容器的大小,但是当从 UITextView 中删除一行时如何减小其高度。正如我所说,我正在使用 AutoLayout
  • 我的意思是使用contentSize 找出所需的高度并将其用作约束常量

标签: ios height uitextview


【解决方案1】:

请按以下方式 -

确保您的 UITextView 滚动已禁用。

添加一个具有默认高度的虚拟 UITextView 高度约束,将其与

连接
IBOutlet (NSLayoutConstraint - textViewHeightConstraint). 

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *textViewHeightConstraint;


- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView{

    CGFloat myMaxSize = 480.0f; 

    CGRect frameRect = textView.frame;
    CGRect rect = [textView.text 
boundingRectWithSize:CGSizeMake(frameRect.size.width, CGFLOAT_MAX)
             options:NSStringDrawingUsesLineFragmentOrigin 
          attributes:@{NSFontAttributeName: textView.font} 
             context:nil];

    CGSize size = rect.size;
    if (size.height > myMaxSize) {
        size.height = myMaxSize;
        [textView setScrollEnabled:YES];
    }

    frameRect.size = size;

    self.textViewHeightConstraint.constant = size.height;  

}

【讨论】:

  • 我试过这段代码,但我没有得到任何我应该得到的改变。我的 textview 在 uiview 中,当 uitextview 内容发生变化时,我想改变 uiview 的高度。我正在使用 Auto布局。
  • 好的,然后尝试更改 UIview 并调用 [view layoutIfNeeded]
  • 不设置框架使用框架来设置约束常量
  • @user3563618 我上面有更新代码,并用我的系统进行了测试。请以同样的方式更改超级视图的高度。
猜你喜欢
  • 2013-06-02
  • 1970-01-01
  • 2011-06-20
  • 1970-01-01
  • 1970-01-01
  • 2014-10-19
  • 1970-01-01
  • 2012-10-19
  • 2013-12-19
相关资源
最近更新 更多