ios - Swift:表格 View 单元格上的渐变

标签 ios swift tableview gradient cagradientlayer

在 tableView 的单元格上,我尝试使用以下 Swift 代码定义渐变:

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {

    var cell:UITableViewCell = self.tableView?.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
    cell.backgroundColor=UIColor.clearColor()
    let gradient : CAGradientLayer = CAGradientLayer()
    var arrayColors:Array<AnyObject> = [UIColor.blackColor().CGColor, UIColor.whiteColor().CGColor]
    gradient.colors=arrayColors
    gradient.frame = cell.bounds
    cell.layer.insertSublayer(gradient, atIndex: UInt32(indexPath.row))

    return cell
 }

行为非常困惑:首次加载 View 时,所有单元格都有白色背景。如果我上下滚动,某些内容的单元格会消失(标题和副标题),并且渐变最终会出现在这些单元格中(随机地,其他一些单元格会保留白色背景)。 它与此强制转换 -> UInt32(indexPath.row) 相关吗?

最佳答案

我有一个类似的问题,我的错误是直接在单元格中插入带有渐变的新层,尝试将新层插入到 backgroundView 中,像这样

let gradient = CAGradientLayer()
// layer setup...
cell.backgroundView = UIView()
cell.backgroundView?.layer.insertSublayer(gradientLayer, atIndex: 0)

希望这对您有所帮助。

关于ios - Swift:表格 View 单元格上的渐变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25556603/

相关文章:

ios - 如何在iOS中从TableView高度的底部到顶部插入动画的TableView行

ios - 使用企业许可证在*任何* iphone 上安装应用程序

ios - 在实例化单元格之前调用 UICollectionView 委托(delegate)方法?

html - iOS 9 移除了使用 CSS 更改某些符号颜色的可能性

ios - viewForAnnotation 返回 nil

swift - TableView 部分更改标题对齐方式

ios - Xcode pin 底部约束不起作用

ios - 可选类型 UILabel 的值未展开。

ios - Twitter profileImageURL 间歇性不加载(iOS Swift)

JavaFX 将问号 TableView 转换为已知类型