【问题标题】:Getting initial layouts correct in UITableViewCell在 UITableViewCell 中获取正确的初始布局
【发布时间】: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


    【解决方案1】:

    这样的绘图需要在drawRect 中进行。当尺寸布局正确时调用它。我遇到了类似的情况,这是放置我的绘图代码的最佳位置,它只会被调用一次,并且可以正确完成。

    所以,你会这样做:

    override func drawRect(rect: CGRect) {
        super.drawRect(rect)
        //draw stuff here
    }
    

    【讨论】:

    • 不,我是说您应该将该代码放在drawRect 中,因为那时您将有适当的边界可用。
    • 哎呀。我尝试在自定义 UITableViewCell 上使用 drawRect() 覆盖来调整图层形状。这实际上奏效了。由于某种原因,这似乎是错误的。在 draw 方法中调整图层似乎违反了某些规定,但您是对的,它确实有效。
    • 我的意思是,如果它能让你感觉更好,你可以使用不同类型的绘图......但如果它有效?
    • 是的,我可以只获取当前上下文,并描画相同的路径,而不是操纵图层。这可能更容易。这既回答了我的问题,又没有回答。这似乎意味着任何基于层的 UITableViewCells 操作都会有问题。但是使用图层的全部原因是避免在自定义视图上实现 drawRect() 方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多