ios - UIView 的宽度不会根据约束改变

标签 ios swift uiview

我有一个 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/

相关文章:

ios - 为什么助手预览失败?

swift - 根据数据动态加载 UIController 的各个部分

ios - 在导入 Swift header 的桥接 header 中导入文件

iOS - 自动布局旋转无法按预期工作

ios - 无法访问通过委托(delegate)传递的数据

ios - glDrawElements 中的参数类型 UnsafePointer<Void>

iphone - 调用方法时 UIView 无法正确显示

ios - UIView 方法 swizzling swift 3

ios - UICollectionView 移动单元格在单击单元格后还原

swift - 从未调用 Deinit 方法 - Swift playground