【问题标题】:UITextField doesn't scale according to width specifiedUITextField 不根据指定的宽度缩放
【发布时间】:2019-05-16 17:39:05
【问题描述】:

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

【问题讨论】:

  • 通过大写您的变量 userName,它是代码突出显示为一个类(如 UITextField)。这使得弄清楚发生了什么变得更加困难。因此进行了编辑。
  • @Jbryson 好的,我不知道,所以我回滚了您的编辑。

标签: ios swift


【解决方案1】:

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

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

【讨论】:

  • 最好使用小写作为变量名的开头 为什么?
  • 另外,你能告诉我框​​架有什么不同
  • 这是一种广泛使用的约定,以帮助保持秩序......类名的大写,例如UITextField,变量小写,例如myTextField.
  • 好吧,会遵循这个约定,但这是允许的,对吧?
  • 可以通过设置.autoresizingMask 属性来使用自动布局的框架。但是,约束可以做更多的事情,并且可以更容易地设计自适应布局(不同的屏幕尺寸和方向)。见:developer.apple.com/library/archive/documentation/…
【解决方案2】:

您可以在创建视图并配置约束后尝试使用updateConstraintslayoutIfNeeded 函数

userName.updateConstraints()
or
userName.layoutIfNeeded()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-14
    • 1970-01-01
    • 1970-01-01
    • 2015-09-23
    • 1970-01-01
    相关资源
    最近更新 更多