我在创建通告UIImageView
时遇到问题。如果要手动将corderRadius
设置为一个值,例如。 50,它将具有圆角。但是,当我尝试将其设置为框架高度或宽度(frame.width / 2
或frame.height / 2
)的一半时,它不起作用。尝试打印时,框架以某种方式(0, 0, 0, 0)
。
这是我的代码,
import UIKit
class TestIconController : UIViewController {
let icon: UIImageView = {
let imageView = UIImageView()
imageView.layer.cornerRadius = imageView.frame.width / 2
imageView.clipsToBounds = true
imageView.layer.masksToBounds = true
imageView.backgroundColor = .red
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
override func viewDidLoad() {
super.viewDidLoad()
loadLogo()
}
func loadLogo() {
view.addSubview(icon)
// Constraints
icon.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
icon.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
icon.heightAnchor.constraint(equalToConstant: 200).isActive = true
icon.widthAnchor.constraint(equalToConstant: 200).isActive = true
}
}
答案 0 :(得分:2)
覆盖此功能。
override func viewDidLayoutSubviews() {
icon.layer.cornerRadius = icon.bounds.size.width / 2
icon.clipsToBounds = true
icon.layer.masksToBounds = true
}
答案 1 :(得分:1)
您也可以为其创建基类以处理面糊;喜欢
class UICirlceImageView : UIImageView {
override open func layoutSubviews() {
super.layoutSubviews();
let layer:CALayer = self.layer;
layer.cornerRadius = self.frame.size.width/2.0;
layer.masksToBounds = true;
}
}
然后,像这样
//let icon: UICirlceImageView = { // You may initialize like this as well
let icon: UIImageView = {
let imageView = UICirlceImageView()
imageView.backgroundColor = .red
//imageView.translatesAutoresizingMaskIntoConstraints = false // Don't know if it is needed
return imageView
}()
注意:鲁沙卜(Rushabh)给出的答案也是正确的。
答案 2 :(得分:0)
您可以创建此扩展名
extension UIImageView {
func setRounded() {
self.layer.cornerRadius = self.frame.width / 2
self.layer.masksToBounds = true
self.clipsToBounds = true
}
}
根据您的情况,您可以在 viewDidLayoutSubviews 呼叫
内icon.setRounded()