设置文本时停止调整UITextField的大小 [英] Stop UITextField resizing when setting text

查看:68
本文介绍了设置文本时停止调整UITextField的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个视图设置,其中布置了4个UITextField和约束设置,因此它在所有设备上看起来都很不错,并且可以按预期工作.我有一个问题,如果我使用TextField.text = @一些长文本"来设置文本;或[TextField setText:@一些长文本"];这会导致文本字段扩展其宽度以适合文本的长度,然后由于其他限制,其他文本字段也将重新调整大小.

如何停止调整文本字段的大小?我想要的是字段保持不变,并且用户如果想要结束时只能滚动文本?

谢谢

解决方案

您只需要更改约束即可.给UITextField一个显式的内部Width约束(或使用约束以其他方式设置或限制其宽度),然后事情就会按照您的期望进行.

请记住,通常,视图大小和位置所有的所有方面都必须由其约束明确配置.但是,现在,您的文本字段具有 no 宽度限制,因此其宽度基于其文本内容(即,它使用内在内容大小来获取其宽度) ).忽略Width约束不是非法的,这就是为什么Interface Builder在设置约束时不会抱怨的原因-但这是合法的,因为存在提供宽度的固有内容大小,因此,这意味着宽度会在以下情况下发生变化:内部文字发生变化.如果那不是您想要的,那就不要这样做-而是提供一个显式的Width约束.

(类似地,文本字段的隐式高度为30,这就是为什么您不必赋予它Height约束的原因.该高度不会随文本内容而变化,因为与一个UILabel,一个文本字段不会将其文本包装在多行上.)

I have a view setup with 4 UITextFields laid out and constraints setup so that it's looking great on all devices and working as expected. I have an issue where by if I set the text using TextField.text = @" some long text "; or [TextField setText:@"some long text"]; it causes the textfield to expand its width to fit the length of the text and then because of the constraints the other textfields resize too.

How can I stop the textfield resizing ? What I would like is the field to stay the same and the user to be able to just scroll the text If they want to get to the end?

Thanks

解决方案

You just need to change the constraints. Give the UITextField an explicit internal Width constraint (or use constraints to set or limit its width in some other way) and then things will behave as you desire.

Remember, in general all aspects of a view's size and position must be unambiguously configured by its constraints. Right now, however, your text field has no Width constraint, so its width is based on its text contents (that is, it uses the intrinsic content size to obtain its width). Omitting the Width constraint is not illegal, which is why Interface Builder did not complain when you set up the constraints - but it is legal only because there is an intrinsic content size that supplies a width, and thus it does mean that the width changes if the internal text changes. If that isn't what you want, then don't do that - supply an explicit Width constraint instead.

(Similarly, a text field has an implicit height of 30, which is why you do not have to give it a Height constraint. This height does not change with the text contents, because, unlike a UILabel, a text field does not wrap its text onto multiple lines.)

这篇关于设置文本时停止调整UITextField的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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