2016-01-25 29 views
0

我想掩蓋UITableView的底部和頂部角落。我發現下面的代碼適用於一個特定的屏幕尺寸(iPhone 6),併產生這些結果:UIView掩蔽無法正常工作與自動佈局

class func maskRowForIndexPath<T>(cell : T ,indexPath: NSIndexPath, count : Int) -> T{ 
     let const = UIScreen.mainScreen().bounds.width * (6/(cell as! UIView).frame.size.width) 
     let cornerRadii = CGSizeMake(const, const) 
     let row = indexPath.row 
     if row == 0 { 
      let maskLayer = CAShapeLayer() 
      maskLayer.path = UIBezierPath(roundedRect: (cell as! UITableViewCell).bounds, byRoundingCorners: UIRectCorner.TopLeft.union(.TopRight), cornerRadii: cornerRadii).CGPath 
      (cell as! UITableViewCell).layer.mask = maskLayer 
     } 

     if row == count-1{ 
      let maskLayer = CAShapeLayer() 
      maskLayer.path = UIBezierPath(roundedRect: (cell as! UITableViewCell).bounds, byRoundingCorners: UIRectCorner.BottomLeft.union(.BottomRight), cornerRadii: cornerRadii).CGPath 
      (cell as! UITableViewCell).layer.mask = maskLayer 
     } 
     return cell 
    } 

,你可以:

enter image description here

它通過將下面的代碼實現看,我添加了一個片段,試圖使角線半徑與屏幕尺寸(實際上是視圖尺寸)成正比:

let const = UIScreen.mainScreen().bounds.width * (6/(cell as! UIView).frame.size.width) 

maskRowForIndexPath方法是我的UITableView內部調用cellForRowAtIndexPath方法:

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

     let row = indexPath.row 
     let info = (indexPath.section == 0) ? firstSectionTitles : secondSectionTitles 
     let cell : AccountHomeTableViewCell = tableView.dequeueReusableCellWithIdentifier("AccountHomeTableViewCell") as! AccountHomeTableViewCell 
     cell.titleLabel.attributedText = attributedTitleForCellString(info[row].title) 
     cell.cellImageView.image = UIImage(named: info[row].imageName) 
     cell.layoutMargins = UIEdgeInsetsZero; 
     UIView.maskRowForIndexPath(cell, indexPath: indexPath, count: info.count) 

     return cell 
    } 

當運行在iPhone 6+(和更小的iPhone 5)屏幕中的應用程序,該視圖被不適當掩蔽:

enter image description here

任何想法如何解決?

謝謝:)

+0

如何將遮罩應用於UITableView?還是這些部分?另外,你的故事板的大小是多少(Any-Any或其他)? – vrwim

+0

將掩碼應用於tableview將不會得到適當的結果 - 例如在有多個部分的情況下(如提供的圖像中)。這是一個tableview,所以如果我圍繞tableview的角落,第一部分的底角將不會被倒圓角以及第二部分的頂角。我沒有使用大小類,因爲它嚴格地是iPhone應用程序。視圖控制器的故事板推斷尺寸是4.7英寸(iPhone 6)。 @vrwim – royherma

+0

您是否嘗試過在tableView(tableView:UITableView,willDisplayCell cell:UITableViewCell,forRowAtIndexPath indexPath:NSIndexPath)中應用mask,而不是在cellForRowAtIndexPath中? – andlin

回答

0

在你cellForRowAtIndexPath您使用的是自定義單元格,並給予圓角半徑在你的方法:

class func maskRowForIndexPath<T>(cell : T ,indexPath: NSIndexPath, count : Int) -> T 

...您使用UITableViewCell。嘗試改變你的customCell課程。

+0

因爲我的自定義單元是UITableViewCell的子類,所以看不到這是怎麼回事,參數類只是對所有的UITableViewCell都適用 – royherma

+0

雖然你的customcell是UITableviewCell的子類,但你必須提及你的customcell而不是你的UITableViewCell,因爲UITableView默認只管理UITableViewCell而不是你的customCell。所以在你的方法改變你的customCell。這將解決您的問題 –

相關問題