2017-02-27 16 views
0

カスタムtableViewのセルで、上に丸みを帯びたコーナーを持つUIViewを作成したいと思います。丸みを帯びたコーナーがUIViewのサイズを変更する

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 

問題はときということである:ここで私は以下の私が行っているビューの丸みを帯びた角を設定するには、この部分の

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 

ベローのUIViewの制約を設定していたコードの一部ですこのコードブロックは、ビューのサイズが変更された丸いコーナーを設定するために使用されます。ここでは、出力コードのこの部分のない

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 
} 
関連する問題