根据内容调整textField的大小 [英] Resize textField Based On Content

查看:95
本文介绍了根据内容调整textField的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

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

推荐答案

您必须使用 UITextView 而不是 UITextField

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

Then, you can use the sizeThatFits method.

但首先你必须知道一条线的高度。您可以使用 lineHeight 获取该信息:

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

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

之后,只需在 viewDidLoad 方法中调用 siteThatFits 方法并设置maxHeight( line * 6 )作为textview-height:

After that, just call the siteThatFits method inside your viewDidLoad method and set the maxHeight (line * 6) as your textview-height:

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

这篇关于根据内容调整textField的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆