ios - UITextField 不根据指定的宽度缩放

标签 ios swift

我想以编程方式创建一个 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/

相关文章:

ios - 如何在 Objective-C 中使用局部变量作为 tableView 的数据源

iphone - 应用程序处于前台模式时如何禁用 iPhone/iPad 自动锁定?

ios - Swift:手势识别器无法识别选择器发送到实例

swift - 显示 = brain.evaluateWithErrorReport(添加了使用 : dictionaryForVaribles) gives an error unless an as!。为什么?

iphone - NSFileSize 是什么实体?

ios - 未收到广告时隐藏广告 View ,然后再次显示

iphone - 如何使状态、选项卡和导航栏像照片应用程序中一样动画

iOS - 类型 'UIView' 没有成员 'AnimationOptions'

macos - 如何使用 Swift 1.2/Cocoa 以编程方式在 NSToolbar 上选择 NSToolbarItem

swift - 我如何通过在 Swift Playground 上按下按钮来调用场景