ios - Swift、约束、UILabel、 anchor 右

标签 ios swift3 nslayoutconstraint

想要的...

enter image description here

由于某种原因,以下内容不起作用:

extension UIView {
    func addWordOnRight() {
        let l = UILabel()

        //l.frame = self.bounds ..?

        l.textAlignment = .right
        l.text = "blah"

        self.addSubview(l)

        let m = self.layoutMarginsGuide
        l.trailingAnchor.constraint(equalTo: m.trailingAnchor, constant: 0).isActive = true
        l.centerYAnchor.constraint(equalTo: m.centerYAnchor, constant: 0).isActive = true
    }
}

如果你 l.frame = self.bounds,它会神秘地锚定到左侧,而不是右侧。

最佳答案

默认情况下,标签将 translatesAutoresizingMaskIntoConstraints 设置为 true,因此 View 会自动添加约束。当您添加自己的约束时,这些约束与已添加的约束发生冲突。 (您应该在控制台中看到很多警告。)

如果您想使用自动布局,请设置l.translatesAutoresizingMaskIntoConstraints = false。您的约束现在应该可以正常工作。

如果您还想设置标签的宽度和高度,也可以使用约束来设置它们(保留框架)。

关于ios - Swift、约束、UILabel、 anchor 右,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41856840/

相关文章:

ios - 我的平移手势识别器非常缓慢且无响应

iphone - 如何知道 iOS 中的 UITextField 是否有空格

iOS 13 : @objc VC. navigationController(_:willShow:animated:):线程违规:预期主线程

ios - 隐藏和显示( subview )按钮或更改标题?

iOS - 横向和纵​​向失败的特征有所不同

ios - 如何使用自动布局将一个 UIView 定位在其他两个 UIView 的中心?

ios - 有什么办法可以将按钮按圆形排列吗?

algorithm - iOS:优化位图模糊算法

ios - 在 UINavigationBar 中单击 "Back"按钮时 UIScrollView 滚动

ios - URLSession 产生 '()' ,而不是预期的上下文结果类型