gpt4 book ai didi

ios - 如何根据其内容调整 UITextView 的大小?

转载 作者:IT王子 更新时间:2023-10-29 07:24:23 26 4
gpt4 key购买 nike

是否有调整 UITextView 大小以符合其内容的好方法?比如说我有一个包含一行文本的 UITextView:

"Hello world"

然后我添加另一行文本:

"Goodbye world"

在 Cocoa Touch 中有没有一种好的方法来获取 rect 来保存 TextView 中的所有行,以便我可以相应地调整父 View ?

作为另一个示例,查看日历应用程序中事件的注释字段 - 注意单元格(及其包含的 UITextView)如何扩展以容纳注释字符串中的所有文本行.

最佳答案

这适用于 iOS 6.1 和 iOS 7:

- (void)textViewDidChange:(UITextView *)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;
}

或在 Swift 中(适用于 iOS 11 中的 Swift 4.1)

let fixedWidth = textView.frame.size.width
let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
textView.frame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)

如果您希望支持 iOS 6.1,那么您还应该:

textview.scrollEnabled = NO;

关于ios - 如何根据其内容调整 UITextView 的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50467/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com