使翻译自动调整大小掩码到约束错误会导致 UITextFields 右侧视图上的布局问题不明确



我不知道让每个对象都翻译自动调整大小MaskIntoConstraint标志false是否是坏习惯,但这是我与此相关的问题; 我有 UITextField 对象,我将其 rightView 设置为 UIImageView,但是当 UIImageView 的翻译自动调整大小掩码到约束属性在调试视图层次结构中设置为 false 时,会出现不明确的布局警告, Apple 的文档在 translatesAutoressizeMaskIntoConstraint 主题下说:

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

但是有UITextField的方法

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

返回接收器右侧叠加视图的绘制位置。

此外,当我尝试在 rightView 和 UITextField 之间给出约束时,它说它们不在同一层次结构下。 那么,为什么将该标志设为错误会导致布局模棱两可呢?

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

我遇到了类似的问题,但就我而言,我忘记了添加翻译自动调整大小掩码到约束为假。

你写的关于翻译自动调整大小掩码到约束的东西是正确的。通常,当您使用设置框架或边界时,它不是很好的一对。

无论如何,我尝试了您的代码,我知道可能会有什么效果;

  • 首先检查您的 UITextField 约束。如果您的约束不适合,那么在添加 rightView 后可能会中断。
  • 其次,使用如下所示的框架初始化您的图像视图;
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会更好 为您的文本字段使用具有最佳分辨率的图像,休息就可以了。

最新更新