【发布时间】:2016-10-02 14:06:01
【问题描述】:
我有一个UITableViewCell 的自定义子类。其中,它有一个UIView 属性,我称之为boxView(例如@IBOutlet var boxView: UIView!)。我正在尝试为这个 boxView 应用一个特殊的边框,一个只有一些圆角的矩形。
我选择使用awakeFromNib() 作为这样做的点:
override func awakeFromNib() {
super.awakeFromNib()
let borderLayer = CAShapeLayer() // for the outline
borderLayer.strokeColor = UIColor.blackColor().CGColor // black line
borderLayer.lineWidth = 1.0 // of width 1
borderLayer.fillColor = nil // no fill
borderLayer.frame = self.boxView.bounds // align the layer with the boxView
borderLayer.path = UIBezierPath(roundedRect: self.boxView.bounds, byRoundingCorners: .BottomRight, cornerRadii: CGSize(width: 10, height: 10)).CGPath // set the path with a UIBezierPath rounding just the bottom right corner
self.boxView.layer.insertSublayer(borderLayer, atIndex: 0) // insert it at the bottom so we can find it later
}
在我的 iPhone 6 上,它运行良好。但在 iPad 上,它出现了错误。它没有应有的宽度。我启用了大小类,但我只是使用任何 x any。 boxView 与容器视图的边距对齐。
通过一些调试打印,我看到在 iPad 上,awakeFromNib() 运行时,宽度为 520。我不确定这个数字来自哪里。考虑到这是一些中间尺寸,我在我的子类中添加了以下方法:
override func layoutSubviews() {
super.layoutSubviews()
if let borderLayer = self.box.layer.sublayers?.first as? CAShapeLayer {
borderLayer.frame = self.boxView.bounds
borderLayer.path = UIBezierPath(roundedRect: self.boxView.bounds, byRoundingCorners: .BottomRight, cornerRadii: CGSize(width: 10, height: 10)).CGPath
}
}
基本上,如果视图大小发生变化,请尝试相应地调整路径。使用更多调试语句,我可以看到视图确实更改为宽度 688。我不确定是什么触发了它。我正在改变单元格的顺序,因为它们已被填充。但并不是所有的视图都会调整大小,所以我最终会修复大部分视图,但不是全部。如果我将它们滚动到屏幕之外,然后再返回,它们似乎最终会调整大小。
使用 UITableViewCell 进行布局调整的正确方法是什么?尤其是初始布局调整?
【问题讨论】:
标签: ios swift uitableview layout autolayout