Swift:TableView单元格上的渐变 [英] Swift: gradient on a cell of a tableview

查看:128
本文介绍了Swift:TableView单元格上的渐变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

On tableView's cells, I'm trying to define a gradient with the following Swift code:

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
 }

此行为非常混乱:首次加载视图时,所有单元格都具有白色背景.如果我上下滚动,则内容的某些单元格消失(标题和字幕),并且渐变最终出现在这些单元格中(随机地,其他一些单元格则保持白色背景). 它与此演员-> UInt32(indexPath.row)有关吗?

The behavior is very chaotic: when the view is first loaded, all cells have a white background. And if I scroll up and down, some content's cells disappear (title and subtitle) and the gradient finally appears in these cells (randomly, some other cells stay with a white background). Is it related to this cast -> UInt32(indexPath.row) ?

推荐答案

渐变是一种视觉装饰.它特定于单元格类.单元格的外观是单元格的责任.然后应在单元格类中定义它.它绝对不属于cellForRowAtIndexPath,它仅应与为正确的行选择正确的单元格有关. 但是,您正在使用该方法配置单元的内部结构,这与排队的工作方式结合在一起会导致所有问题.

The gradient is a visual ornamentation. It is specific to the cell class. How the cell looks is the responsibility of the cell. It should be defined in the cell class then. It absolutely does not belong to the cellForRowAtIndexPath which should be solely about choosing the right cell for the right row. But you are configuring the internals of the cell in that method and this, combined with the way how queueing works, causes all the issues.

1)创建UITableViewCell的子类(从编程上来说,IB ..并不重要)

1) Create a subclass of UITableViewCell (programatically, IB..it doesn't really matter)

2)将awakeFromNib或layoutSubviews中的图层添加到backroundView属性.

2) Add the layer in awakeFromNib or layoutSubviews to the backroundView property.

3)将单元格注册到tableViewController的viewDidLoad中.

3) register the cell in viewDidLoad in your tableViewController.

这篇关于Swift:TableView单元格上的渐变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆