ios - UITableViewCell 的层在 heightForRowAt IndexPath 之后没有更新

标签 ios swift uitableview cagradientlayer heightforrowatindexpath

我正在更改每个 TableViewCell 的大小:

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 60
}

然后,在自定义单元格类中,我将“gradientLayer”作为子层插入到单元格的图层属性中:

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    ...
    gradientLayer.frame = self.layer.bounds
    layer.insertSublayer(gradientLayer, at: 0)
    ...
}

但是,渐变并没有填满整个单元格: enter image description here

有谁知道为什么会这样/我该如何解决?

谢谢。

最佳答案

如果您使用普通的 UITableViewCell :

 override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100.0
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath)

        // ...

        let gradient =  CAGradientLayer()
        gradient.frame = cell.contentView.frame
        gradient.colors = [UIColor.blue.cgColor, UIColor.yellow.cgColor]
        gradient.locations = [0.0, 1.0]
        cell.contentView.layer.insertSublayer(gradient, at: 0)

        // ...

        return cell
    }

您需要确保将渐变添加到 contentView 的层。

这会很好用。

如果您使用自定义 UITableViewCell 类:

现在,如果您使用的是自定义单元格类,则需要像这样重写layoutSubviews() 方法:

override func layoutSubviews() {
    super.layoutSubviews()

    gradient.frame = contentView.frame
}

这确保您的渐变框架在任何时候始终等于您的 contentView 框架。

您的自定义单元类将如下所示:

class CustomTableCell: UITableViewCell {

    lazy var gradient : CAGradientLayer = {
        var gradient = CAGradientLayer()
        gradient.colors = [UIColor.blue.cgColor, UIColor.yellow.cgColor]
        gradient.locations = [0.0, 1.0]
        self.contentView.layer.insertSublayer(gradient, at: 0)
        return gradient
    }()

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        // ...

    }

    override func layoutSubviews() {
        super.layoutSubviews()

        // ...

        gradient.frame = contentView.frame

        // ...

    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        // ...
    }


}

如果您还有其他问题,请告诉我!

关于ios - UITableViewCell 的层在 heightForRowAt IndexPath 之后没有更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46333668/

相关文章:

ios - 在 iOS 应用程序中打开链接以关注 Google Plus 页面?

ios - 将 FaceBook 登录添加到 Cocos2d Xcode 项目

ios - 如何查询最近3天内创建的对象? [parse.com]

ios - 如果第一个通知在 swift 中被忽略,则安排第二个通知(或者如果通知被忽略则完成任何操作)

ios - Xamarin UITableView 不会滚动

iphone - 不会调用 canMoveRowAtIndexPath - 但会调用 canEditRowAtIndexPath

ios - 这个 objective-c 变量初始化方式是否正确?

ios - 如何在 libComponentLogger 中记录线程名称

ios - 删除 UITableView 中的行需要太多时间

ios - 如果在另一个表更新后调用得太快,tableView.reloadRows 会闪烁