在UITableViewCell中获得正确的初始布局

时间:2016-06-02 17:34:04

标签: ios swift uitableview layout autolayout

我有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。 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进行布局调整的正确方法是什么?特别是,初始布局调整?

1 个答案:

答案 0 :(得分:2)

这样的绘图需要在json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as? NSDictionary 中进行。在正确布置尺寸时调用它。我把头撞到了类似的情况,这是把我的绘图代码放在一次只能调用一次并且正确完成的最佳位置。

所以,你做了:

drawRect
相关问题