Label under image in UIButton

后端 未结 30 2010
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 15:53

I\'m trying to create a button which has some text beneath the icon (sorta like the app buttons) however it seems to be quite difficult to achieve. Any ideas how can I go ab

30条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 16:42

    Localization Friendly Solution:

    So many great solutions guys, but I'd like to add a note here for those who use localization.

    You need to reverse the left and right EdgeInstets values to get the button laid out correctly in case of a change of language direction from LtR to RtL.

    Using a similar solution I'd implement it as follows:

    extension UIButton {
    
        func alignVertical(spacing: CGFloat, lang: String) {
            guard let imageSize = self.imageView?.image?.size,
                let text = self.titleLabel?.text,
                let font = self.titleLabel?.font
            else { return }
    
            let labelString = NSString(string: text)
            let titleSize = labelString.size(
                withAttributes: [NSAttributedString.Key.font: font]
            )
    
            var titleLeftInset: CGFloat = -imageSize.width
            var titleRigtInset: CGFloat = 0.0
    
            var imageLeftInset: CGFloat = 0.0
            var imageRightInset: CGFloat = -titleSize.width
    
            if Locale.current.languageCode! != "en" { // If not Left to Right language
                titleLeftInset = 0.0
                titleRigtInset = -imageSize.width
    
                imageLeftInset = -titleSize.width
                imageRightInset = 0.0
            }
    
            self.titleEdgeInsets = UIEdgeInsets(
                top: 0.0,
                left: titleLeftInset,
                bottom: -(imageSize.height + spacing),
                right: titleRigtInset
            )
            self.imageEdgeInsets = UIEdgeInsets(
                top: -(titleSize.height + spacing),
                left: imageLeftInset,
                bottom: 0.0,
                right: imageRightInset
            )
            let edgeOffset = abs(titleSize.height - imageSize.height) / 2.0;
            self.contentEdgeInsets = UIEdgeInsets(
                top: edgeOffset,
                left: 0.0,
                bottom: edgeOffset,
                right: 0.0
            )
        }
    }
    
    

提交回复
热议问题