简体   繁体   中英

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:

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?

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
        )
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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