我創建了一個自定義 UIView,其中包含一個包含幾個方形子視圖的子視圖,這些子視圖使用布局約束來調整大小。我希望每個子視圖都是圓形的,因此我在陣列中保存對視圖的參考,然后在 layoutSubviews 方法中遍歷視圖陣列并應用一個為 view.bounds.height 一半的角半徑。

問題是,這只在 70% 的情況下有效。有時視圖似乎不知道它的邊界并且視圖呈現為正方形。

我可能正在接近這一切都是錯誤的......有人對我有什么建議嗎?在哪里可以安全地應用圓角半徑以使其始終呈現為完美的圓?
謝謝
uj5u.com熱心網友回復:
最可靠的管理方法是子類化UIView并讓它處理自己的舍入。
例如:
class RoundView: UIView {
override func layoutSubviews() {
super.layoutSubviews()
// this assumes constraints keep
// self at a 1:1 ratio (square)
layer.cornerRadius = bounds.height * 0.5
}
}
這個簡單的控制器示例:
class RoundDemoVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let colors: [UIColor] = [
.systemRed, .systemGreen, .systemBlue
]
let widths: [CGFloat] = [
200, 140, 140
]
let xPos: [CGFloat] = [
20, 120, 180
]
let g = view.safeAreaLayoutGuide
for i in 0..<colors.count {
let v = RoundView()
v.backgroundColor = colors[i]
view.addSubview(v)
v.translatesAutoresizingMaskIntoConstraints = false
v.widthAnchor.constraint(equalToConstant: widths[i]).isActive = true
// make it square
v.heightAnchor.constraint(equalTo: v.widthAnchor).isActive = true
v.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: xPos[i]).isActive = true
v.centerYAnchor.constraint(equalTo: g.centerYAnchor).isActive = true
}
}
}
產生這個輸出:

無需遍歷子視圖并根據幀大小設定值......您需要做的就是設定大小/位置約束。
uj5u.com熱心網友回復:
Donmag 的示例很酷。另外,您可以這樣做,而無需向 layoutsubview 撰寫代碼。您必須在 中添加after adding the constraints子視圖的此設定for iteration。
.......
....... // constraint settings
subView.layoutIfNeeded()
subView.layer.cornerRadius = subView.frame.size.height/2
uj5u.com熱心網友回復:
override func layoutSubviews() {
super.layoutSubviews()
// This is the place to apply corner radius
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/463809.html
