【问题标题】:Making translatesAutoResizingMaskIntoConstraints false causes ambiguous layout issue on UITextFields rightview使 translatesAutoResizingMaskIntoConstraints 为 false 会导致 UITextFields rightview 上的布局不明确问题
【发布时间】:2019-03-04 04:43:30
【问题描述】:

我不知道让每个对象 translatesAutoresizingMaskIntoConstraints 标志为 false 是否是坏习惯,但这是我与此相关的问题; 我有 UITextField 对象,我将它的 rightView 设置为 UIImageView 但是当 UIImageView 的 translatesAutoresizingMaskIntoConstraints 属性在调试视图层次结构中设置为 false 时出现不明确的布局警告, 苹果的文档在 translatesAutoresizingMaskIntoConstraints 主题下说:

如果您想使用自动布局来动态计算视图的大小和>位置,则必须将此属性设置为 false,然后>为视图提供一组明确、不冲突的约束。

但是有 UITextField 的方法

open func rightViewRect(forBounds bounds: CGRect) -> CGRect

那个

返回接收者右侧覆盖视图的绘制位置。

此外,当我尝试在 rightView 和 UITextField 之间施加约束时,它表示它们不在同一层次结构下。 那么为什么将该标志设置为 false 会导致布局不明确呢?

let imageView = UIImageView(image: UIImage(named: "infoIcon"))
imageView.contentMode = .scaleAspectFit
imageView.translatesAutoresizingMaskIntoConstraints = false //this line causes ambiguous layout
imageView.widthAnchor.constraint(equalToConstant: 15).isActive = true
textField.rightViewMode = .unlessEditing
textField.rightView = imageView

【问题讨论】:

    标签: swift uitextfield autoresizingmask


    【解决方案1】:

    我遇到了类似的问题,但在我的情况下,我忘记了 add translatesAutoresizingMaskIntoConstraints 为 false。

    您写的有关 translatesAutoresizingMaskIntoConstraints 的内容是正确的。当您使用设置框架或边界时,通常它不是很好的一对。

    不管怎样,我试过你的代码,我知道可能会产生什么效果;

    • 首先检查您的 UITextField 约束。如果您的约束条件不合适,则添加 rightView 后可能会中断。
    • 其次,使用如下框架初始化您的 imageView;
    let imageView = UIImageView(frame: .zero)
    imageView.translatesAutoresizingMaskIntoConstraints = false
    imageView.image = UIImage(named: "logo") imageView.contentMode = .scaleAspectFit
    imageView.widthAnchor.constraint(equalToConstant: 15).isActive = true
    textField.rightViewMode = .always 
    textField.rightView = imageView
    
    • 最后我认为最好不要使用imageView.widthAnchor.constraint(equalToConstant: 15).isActive = true 为您的文本字段使用具有最佳分辨率的图像,然后休息就可以了。

    【讨论】:

      猜你喜欢
      • 2019-06-21
      • 2012-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多