我想以编程方式创建一个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));
答案 0 :(得分:2)
首先,最好在变量名的开头使用小写字母-而不是
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
答案 1 :(得分:0)
创建视图并配置约束后,您可以尝试使用updateConstraints或layoutIfNeeded函数
userName.updateConstraints()
or
userName.layoutIfNeeded()