首页 > 解决方案 > UITextField 不根据指定的宽度缩放

问题描述

我想以编程方式创建一个 UITextField 并相应地设置它的样式。我创建我的领域

let userName = UITextField(frame: CGRect(x: 60, y: 60, width: 200.00, height: 200));
userName.placeholder = "Username";
userName.textAlignment = NSTextAlignment.left;
userName.font = UIFont(name: "SpaceGrotesk-Light", size: 20.0);
userName.setBottomBorder()
view.addSubview(userName)
userName.translatesAutoresizingMaskIntoConstraints = false;
userName.leftAnchor.constraint(equalTo: view.leftAnchor,constant: 70).isActive = true;
userName.topAnchor.constraint(equalTo: WelcomeText.topAnchor,constant: 70).isActive = true;

这可行,但是字段的宽度与占位符相同并且不会增加,但是如果您开始输入它,那么字段的宽度会根据输入的文本增加。
我是初学者,不知道为什么会这样。
我试图增加宽度,但没有运气。

let userName = UITextField(frame: CGRect(x: 60, y: 60, width: 400.00, height: 200));

标签: iosswift

解决方案


首先,最好使用小写作为变量名的开头 - 所以而不是

let UserName = UITextField(...)

利用

let userName = UITextField(...)

但是,这与大小无关。

您似乎正在尝试将显式框架与自动布局“混合和匹配”。使用其中一种。

试试这样:

// we'll use constraints, so no need to set a frame
let UserName = UITextField();
UserName.placeholder = "Username";
UserName.textAlignment = NSTextAlignment.left;
UserName.font = UIFont(name: "SpaceGrotesk-Light", size: 20.0);
UserName.setBottomBorder()
view.addSubview(UserName)

// this says "use auto-layout constraints"
UserName.translatesAutoresizingMaskIntoConstraints = false;

UserName.leftAnchor.constraint(equalTo: view.leftAnchor,constant: 70).isActive = true;
UserName.topAnchor.constraint(equalTo: WelcomeText.topAnchor,constant: 70).isActive = true;

// now, set your explicit width
UserName.widthAnchor.constraint(equalToConstant: 200.0).isActive = true

或者,如果您希望它根据其父视图的宽度进行拉伸:

// you have 70-pts padding from the left, so constrain to 70-pts padding from the right
// note that it should be negative (because you want it *from* the right-edge)
UserName.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -70).isActive = true

推荐阅读