2014-08-28 34 views
0

上的tableView的細胞的細胞梯度,我試圖定義具有以下斯威夫特代碼梯度:斯威夫特:在實現代碼如下

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)?

+0

嘗試用@IBOutlet無功表上添加您的實現代碼如下:UITableView的! 並在你的func tableView結束時添加table.reloadData() – 2014-08-28 20:48:47

+0

檢查了這一點:https://github.com/rlease/GradientTableExample - 發現上次我正在尋找類似的東西。也許有幫助。 – derdida 2014-08-28 22:10:52

+0

您可能已經忘記明確定義顏色的「位置」。我知道這只是可選的,但爲了安全起見,你知道;您不需要將新的漸變圖層添加到重複使用的單元格,其中_already_具有漸變圖層;並且圖層應該插入到第0個索引中,我沒有明白爲什麼要將它插入到第'row'索引處。那是什麼意思? – holex 2015-03-03 16:28:43

回答

0

我有一個類似的問題,我的失誤直接在單元格中插入梯度新圖層,請嘗試將新的層到backgroundView像這樣

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

希望這有助於。

1

梯度是一個視覺紋飾。它是特定於單元類的。細胞看起來是細胞的責任。它應該在單元類中定義。它絕對不屬於cellForRowAtIndexPath,它應該完全關於爲正確的行選擇正確的單元格。 但是,您正在配置該方法的單元內部結構,並結合排隊工作方式導致所有問題。

1)創建的UITableViewCell的子類(編程,IB..it其實並不重要)

2)awakeFromNib或layoutSubviews添加層到backroundView財產。

3)在tableViewController註冊在viewDidLoad中的單元格。