简体   繁体   English

如何在图标和外框下创建带有标题的按钮

[英]how to create button with title under icon and outside frame

I want create button with image like this 我想和喜欢的图像创建按钮,

and this is my code but it't true with other model iPhone: 这是我的代码,但其他型号的iPhone并非如此:

extension ButtonWithImage {
func alignVertical(spacing: CGFloat = 6.0) {
    guard let imageSize = self.imageView?.image?.size else { return }
    guard let titleSize = titleLabel?.intrinsicContentSize else{return}

    // Title Edge Insets
    let titleEdgeInsets = UIEdgeInsets(top: 0.0 ,
                                       left: -imageSize.width,
                                       bottom: -(self.frame.size.height + 2*spacing),
                                       right: 0.0)
    self.titleEdgeInsets = titleEdgeInsets

    self.imageEdgeInsets = UIEdgeInsets(top: 0.0,
                                        left: 0.0,
                                        bottom: 0.0,
                                        right: -titleSize.width)

    self.contentEdgeInsets = UIEdgeInsets(top: spacing,//edgeOffset,
                                          left: 0.0,
                                          bottom: spacing,//edgeOffset,
                                          right: 0.0)
}
}

what is value of bottom in titleEdgeInsets to working the same with any model iPhone? 在任何型号的iPhone上,titleEdgeInsets中的bottom值是多少?

please use below extension for simple use 请使用以下扩展名以方便使用

extension UIButton {

    func alignCenter(withPadding: 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),
            left: 0.0,
            bottom: 0.0,
            right: -titleLabelSize.width
        )

        self.titleEdgeInsets = UIEdgeInsets(
            top: 0.0,
            left: -imageViewSize.width,
            bottom: -(totalHeight - titleLabelSize.height),
            right: 0.0
        )

        self.contentEdgeInsets = UIEdgeInsets(
            top: 0.0,
            left: 0.0,
            bottom: titleLabelSize.height,
            right: 0.0
        )
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM