ios 根据内容调整 textField 的大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28389913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 04:43:54  来源:igfitidea点击:

Resize textField Based On Content

iosswiftresizetextfield

提问by Michael Voccola

How can a textField be resized based on content while using auto-layout in an iOS application written in Swift?

在用 Swift 编写的 iOS 应用程序中使用自动布局时,如何根据内容调整 textField 的大小?

The text field will resize as necessary to fit its content when the view loads as well as while the user is typing.

当视图加载以及用户输入时,文本字段将根据需要调整大小以适应其内容。

Ideally, the text field would stop resizing at a certain point, say, 6 lines, and become scrollable.

理想情况下,文本字段将在某个点停止调整大小,例如 6 行,并变为可滚动。

回答by Christian

You have to use an UITextViewinstead of an UITextField.

您必须使用 anUITextView而不是UITextField

Then, you can use the sizeThatFitsmethod.

然后,您可以使用该sizeThatFits方法。

But first you have to know how high one line will be. You can get that information by using lineHeight:

但首先你必须知道一条线有多高。您可以使用lineHeight以下方法获取该信息:

var amountOfLinesToBeShown: CGFloat = 6
var maxHeight: CGFloat = yourTextview.font.lineHeight * amountOfLinesToBeShown

After that, just call the sizeThatFitsmethod inside your viewDidLoadmethod and set the maxHeight (line * 6) as your textview height:

之后,只需sizeThatFits在您的viewDidLoad方法中调用该方法并将 maxHeight ( line * 6)设置为您的文本视图高度:

yourTextview.sizeThatFits(CGSizeMake(yourTextview.frame.size.width, maxHeight))

回答by user44776

Swift 3

斯威夫特 3

var textView : UITextView!

override func viewDidLoad() {
    super.viewDidLoad()
    textView = UITextView()
    textView.sizeThatFits(CGSize(width: textView.frame.size.width, height: textView.frame.size.height))
}