2017-02-27 130 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 
}