在 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/