image disappears when styling class to make a round image(样式类制作圆形图像时图像消失)
问题描述
class RoundImage: UIImageView {
override func awakeFromNib() {
super.awakeFromNib()
setupView()
}
...
func setupView() {
self.layer.borderWidth = borderWidth
self.layer.borderColor = borderColor
self.clipsToBounds = clip
self.layer.cornerRadius = self.frame.size.width / 2
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
setupView()
}
}
我正在使用以下类来设置我的 UIImageViews 的样式.我想让它们变成圆形.当我添加以下代码行 self.layer.cornerRadius = self.frame.size.width/2
使这成为可能时,我的整个图像消失了.当我使用像 50 这样的硬编码值(因为我的图像的宽度是 100)时,它可以工作.但是当我想以这种方式使其动态化时,它似乎失败了.
I am using the following class to style my UIImageViews. I want to make them circular. When I add the following line of code self.layer.cornerRadius = self.frame.size.width / 2
to make this possible, my entire image disappears.
When I use a hardcoded value like 50 (since the width of my image is 100) it works. But when I want to make it dynamic this way, it seems to fail.
我在这里错过了什么?
推荐答案
我前几天遇到了这个问题.您应该在图层修改之前添加 layoutIfNeeded()
.
I faced with this problem a few days ago.
You should add layoutIfNeeded()
before layer modifications.
在你的情况下:
func setupView() {
self.layoutIfNeeded()
self.layer.borderWidth = borderWidth
self.layer.borderColor = borderColor
self.clipsToBounds = clip
self.layer.cornerRadius = self.frame.size.width / 2
}
这篇关于样式类制作圆形图像时图像消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!