自定义按钮,文本,图像居中并更改按钮大小

时间:2018-12-19 15:54:04

标签: swift xcode custom-button

我想使用文字和图像制作自定义按钮。我使用下面的代码来制作图像,在绿框中间的文本,并更改​​绿框的大小,但我不能。

我如何在绿色框的中央制作图像,文本并更改绿色框的大小?

button with text and image

@IBDesignable类MyButton:UIButton {

覆盖函数func layoutSubviews(){

    super.layoutSubviews()
    updateCornerRadius()
    centerVertically()
}

@IBInspectable var rounded: Bool = false {
    didSet {
        updateCornerRadius()
    }
}
func updateCornerRadius() {
    layer.cornerRadius = 15
    frame.size = CGSize(width: 100, height: 100)
}
func centerVertically(padding: CGFloat = 6.0) {
    guard
        let imageViewSize = self.imageView?.frame.size,
        let titleLabelSize = self.titleLabel?.frame.size else {
            return
    }
    let totalHeight = imageViewSize.height + titleLabelSize.height + padding
    self.imageEdgeInsets = UIEdgeInsets(
        //top: -(totalHeight - imageViewSize.height),
        top: -(100 - totalHeight)/2 ,
        left: 0.0,
        bottom: 0.0,
        right: -titleLabelSize.width
    )
    self.titleEdgeInsets = UIEdgeInsets(
        top: 0.0,
        left: -imageViewSize.width,
        bottom: -(totalHeight - titleLabelSize.height),
        //bottom: (100 - totalHeight)/2,
        right: 0.0
    )
    self.contentEdgeInsets = UIEdgeInsets(
        top: 0.0,
        left: 0.0,
        bottom: titleLabelSize.height,
        right: 0.0
    )
}

}

0 个答案:

没有答案