我想以编程方式创建一个 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));
最佳答案
首先,最好使用小写字母作为变量名的开头 - 所以而不是
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
或者,如果您希望它根据其父 View 的宽度进行拉伸(stretch):
// 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
关于ios - UITextField 不根据指定的宽度缩放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56173909/