如何使自定义舍入UIImageView子类?

时间:2017-04-19 09:38:07

标签: swift uiimageview storyboard uikit

我想进行自定义轮次UIImageView并在故事板中显示。

我接下来做了:

@IBDesignable
class RoundedImageView: UIImageView {
    override init(image: UIImage?) {
        super.init(image: image)
        super.layer.cornerRadius = super.frame.size.height / 2
        self.layer.cornerRadius = self.frame.size.height / 2    
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        super.layer.cornerRadius = super.frame.size.height / 2
        self.layer.cornerRadius = self.frame.size.height / 2
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        super.layer.cornerRadius = super.frame.size.height / 2
        self.layer.cornerRadius = self.frame.size.height / 2
    }
} 

我在storyboard中的imageView是选中的RoundedImageView类。 但在故事板中,它仍然显示为矩形。我怎么才能意识到这一点? 当我运行代码时,它是圆形的。 感谢

1 个答案:

答案 0 :(得分:12)

您应该在应用layouts后设置半径。

@IBDesignable
class RoundedImageView: UIImageView {
    override init(image: UIImage?) {
        super.init(image: image)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        self.layer.cornerRadius = self.frame.size.height / 2
        self.clipsToBounds = true
    }
}