2017-02-27 91 views
0

在自定義tableView單元格中,我想創建頂部帶圓角的UIView。下面是代碼,其中我設置的UIView的制約圓角改變UIView大小

headerView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 8).isActive = true 
headerView.topAnchor.constraint(equalTo: self.topAnchor, constant: 4).isActive = true 
headerView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -8).isActive = true 
headerView.heightAnchor.constraint(equalToConstant: 40).isActive = true 

這部分的波紋管設置的觀點我已經做了圓角以下部分:

self.layoutIfNeeded() 
let rectShape = CAShapeLayer() 
rectShape.bounds = headerView.layer.frame 
rectShape.position = headerView.center 
rectShape.path = UIBezierPath(roundedRect: headerView.layer.bounds, byRoundingCorners: [ .topLeft, .topRight], cornerRadii: CGSize(width: 10, height: 10)).cgPath 
headerView.layer.backgroundColor = UIColor.green.cgColor 
headerView.layer.mask = rectShape 

的問題是,當這個代碼塊用來設置圓角視圖的大小是變化的。下面是輸出

enter image description here

而結果沒有的這部分代碼如下:

enter image description here

我的問題是,爲什麼視圖大小變化?我做錯了什麼?

+0

我不確定,但我認爲這可能是因爲您正在更改視圖的「圖層」,從而影響自動佈局約束。如果你想要做的只是在視圖的四角,那就沒有必要使用'CAShapeLayer' –

+0

我想只在頂部有圓角,所以這就是我使用CAShapeLayer的原因 –

回答

0

它,因爲一旦頭視圖的約束正在調整你的CAShapeLayer不會自動調整大小。每當視圖調整大小時,您都需要更新路徑:

let headerView: UIView! 

    override func awakeFromNib() { 
    super.awakeFromNib() 

    headerView = UIView(frame: bounds) 
    headerView.frame = bounds 

    headerView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 8).isActive = true 
    headerView.topAnchor.constraint(equalTo: self.topAnchor, constant: 4).isActive = true 
    headerView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -8).isActive = true 
    headerView.heightAnchor.constraint(equalToConstant: 40).isActive = true 


    let rectShape = CAShapeLayer() 
    rectShape.bounds = headerView.layer.frame 
    rectShape.position = headerView.center 

    headerView.layer.backgroundColor = UIColor.green.cgColor 
    headerView.layer.mask = rectShape 
    } 

    override func layoutSubviews() { 
    super.layoutSubviews() 

    rectShape.path = UIBezierPath(roundedRect: headerView.layer.bounds, byRoundingCorners: [ .topLeft, .topRight], cornerRadii: CGSize(width: 10, height: 10)).cgPath 
    } 

我用awakeFromNib作爲示例。您的視圖設置可能在您的自定義UITableViewCell類中有所不同。

+0

謝謝!這是正確的答案。只是我想補充說rectShape的聲明必須在awakeFromNib之外,否則你會在layoutSubviews方法中出錯 –

0

很可能,您在獲取headerView界限之前視圖的大小已調整爲適合表格。

如果在子類的UIView,你應該

override func layoutSubviews() { 
    // update path and mask here 
}