gpt4 book ai didi

ios - 圆角改变 UIView 大小

转载 作者:行者123 更新时间:2023-11-28 06:24:12 25 4
gpt4 key购买 nike

在自定义 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

这部分的波纹管设置圆角 View 我做了以下事情:

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

问题是,当此代码块用于设置圆角时, View 的大小会发生变化。这是输出

enter image description here

没有这部分代码的结果如下:

enter image description here

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

最佳答案

这是因为一旦标题 View 的约束被调整大小时,您的 CAShapeLayer 不会自动调整大小。每当调整 View 大小时,您都需要更新路径:

  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 为例。您的 View 设置在您的自定义 UITableViewCell 类中可能有所不同。

关于ios - 圆角改变 UIView 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42490318/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com