我有一个 UIView,我正在绘制并将 subview 添加到另一个 UIView。
这用作分隔符,因此它需要 1px 高和添加它的 View 的宽度。
这是我目前的代码:
var underline = UIView()
underline.frame = CGRectMake(0, 37, backgroundSection.bounds.size.width, 1)
underline.backgroundColor = UIColor.whiteColor()
backgroundSection.addSubview(underline)
这不会将 UIView 的宽度绘制为与 backgroundSection 相同的宽度。这将其绘制为与约束调整 View 大小时 backgroundSection 在 IB 上的外观相同的宽度。
我可以将 backgroundSection 的 clipToBounds 设置为 true,但我在 backgroundSection 上有一个阴影,如果将其设置为 true,该阴影将被删除。
我该如何解决这个问题。
谢谢, 亚历克斯
最佳答案
在使用约束时不应使用框架设置。自动布局将为您完成所有框架设置。
相反,您需要向 View 添加约束:
var underline = UIView()
backgroundSection.addSubview(underline)
// These two lines will add horizontal and vertical constraints pinning the underline view to backgroundSection's edges
backgroundSection.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[view]|", options: nil, metrics: nil, views: ["view": underline]))
backgroundSection.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options: nil, metrics: nil, views: ["view": underline]))
关于ios - UIView 的宽度不会根据约束改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28816633/