圆角改变UIView的大小

时间:2017-02-27 16:03:55

标签: ios swift uiview autolayout constraints

在自定义tableView单元格中,我想在顶部创建带圆角的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

我的问题是为什么视图大小会发生变化?我做错了什么?

2 个答案:

答案 0 :(得分:1)

这是因为一旦调整了Header View的约束,你的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类的视图设置可能有所不同。

答案 1 :(得分:0)

很可能,在调整视图大小以适合表格之前,您将获得headerView bounds

如果在子类UIView中,你应该

requests