[英]How to get CGFloat value from NSLayoutConstraints?
我正在屏幕上工作,我想让这个配置文件视图循环。 但我没有得到高度或宽度从imageView.frame.height
在使用它layer.cornerRadius
。 请帮我。 谢谢。
这是代码供参考。
private func addImageView() {
topView.addSubview(profilePicView)
NSLayoutConstraint.activate([
profilePicView.centerXAnchor.constraint(equalTo: topView.centerXAnchor),
profilePicView.widthAnchor.constraint(equalTo: topView.heightAnchor, multiplier: 0.3)
])
profilePicViewTopAnchor = profilePicView.topAnchor.constraint(equalTo: view.topAnchor, constant: 64)
profilePicViewTopAnchor?.isActive = true
profilePicViewHeightAnchor = profilePicView.heightAnchor.constraint(equalTo: topView.heightAnchor, multiplier: 0.3)
profilePicViewHeightAnchor?.isActive = true
}
而我正试图获得价值,
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
print((profilePicViewHeightAnchor?.constant)!)
profilePicView.layer.cornerRadius = (profilePicViewHeightAnchor?.constant)! / 2
profilePicView.clipsToBounds = true
}
解决了
在每个人的帮助下,我得到了这个解决方案,对我来说非常好,
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let radius = redView.frame.height * 0.3
profilePicView.layer.cornerRadius = radius / 2
profilePicView.clipsToBounds = true
self.view.layoutIfNeeded()
}
谢谢你们所有人。 真的很感激帮助。
这一定是因为你正在访问的时间frame
为imageView
,布局约束不被奠定了autolayout
。 因此,如果您的imageView
位于UIViewController
类中,那么您应该override
以下方法,然后访问width
和height
。
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
print(imageView.frame.height)
}
如果imageView
在自定义视图中,那么您可以override
以下方法然后访问该frame
,
override func layoutSubviews() {
super.layoutSubviews()
print(imageView.frame.height)
}
请试试这对你有帮助。
imageView.layer.cornerRadius = imageView.frame.size.height / 2
imageView.clipsToBounds = true
确保imageView的高度和宽度相同。 谢谢
你也可以使用ViewDidAppear。因为此时Autolayout引擎开始布局Constraint。
override func viewDidAppear() {
super.viewDidAppear()
print(imageView.frame.height)
}
试试这个扩展:
extension UIView {
@IBInspectable
/// Should the corner be as circle
public var circleCorner: Bool {
get {
return min(bounds.size.height, bounds.size.width) / 2 == cornerRadius
}
set {
cornerRadius = newValue ? min(bounds.size.height, bounds.size.width) / 2 : cornerRadius
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.