ios - TableView背景渐变毛刺

标签 ios swift uitableview cagradientlayer

我使用以下代码为表格 View 设置了渐变图层:

func setGradientToTableView(_ topColor:UIColor, _ bottomColor:UIColor) {

    let gradientBackgroundColors = [topColor.cgColor, bottomColor.cgColor]
    let gradientLocations = [0.0,1.0]

    let gradientLayer = CAGradientLayer()
    gradientLayer.colors = gradientBackgroundColors
    gradientLayer.locations = gradientLocations as [NSNumber]

    gradientLayer.frame = tableView.bounds
    let backgroundView = UIView(frame: tableView.bounds)
    backgroundView.layer.insertSublayer(gradientLayer, at: 0)
    tableView.backgroundView = backgroundView

}

还有这个:

setGradientToTableView(UIColor(red: 125/255.0, green: 125/255.0, blue: 125/255.0, alpha: 1.0), UIColor(red: 125/255.0, green: 125/255.0, blue: 0/255.0, alpha: 1.0)).

当我运行应用程序时,问题就来了。渐变层将是 Storyboard中选择的设备和方向的 TableView 的大小。

有人知道怎么解决吗? - 顺便说一句,我对表格 View 的约束是导航栏底部、前导、尾随和安全区域底部

编辑:这是截图

enter image description here

最佳答案

可能的问题是您在 viewDidLoad() 方法中设置了渐变,其中 TableView 尚未绘制,其框架是 XIB/storyboard 的默认框架。 你应该在 didLayoutSubviews() 中这样调用它:

var gradientLayer: CAGradientLayer?
func didLayoutSubviews() {
    if (gradientLayer == nil) {
        setGradientToTableView(UIColor(red: 125/255.0, green: 125/255.0, blue: 125/255.0, alpha: 1.0), UIColor(red: 125/255.0, green: 125/255.0, blue: 0/255.0, alpha: 1.0))
    }
}

在您的类中保留对渐变图层的引用,以确保您只设置一次渐变,因为 didLayoutSubviews 被调用了多次。

关于ios - TableView背景渐变毛刺,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48044227/

相关文章:

iOS:在 pod 中使用 Segment-Firebase 时构建 Xcode 项目时出错

ios - CloudKit 向其他用户推送通知

ios - 如何在 Swift 中从我的应用程序打开 iphone 应用程序?

ios - 如何在 iOS 9、swift 2 中正确覆盖触摸功能

iphone - 我如何判断 UITableViewCell 之外的内容被触摸?

swift - tableView 中的单元格在按下时没有反应

iphone - 如何知道 tableview 大小 xcode iphone?

json - Swift 从循环内部追加到数组

objective-c - 核心数据 : keypath name not found in entity

iphone - 可编辑的表格 View 单元格