iOS 之 UIButton 中图片在文字上方的完美解决方案

  • Swift

import Foundation
import UIKit

enum UIButtonImageTitlePositionType {
    case imageLeftTitleRight
    case imageRightTitleLeft
    case imageUpTitleDown
    case imageDownTitleUp
}

extension UIButton {
    func adjustsImageTitlePosition(type: UIButtonImageTitlePositionType = .imageUpTitleDown, spacing: CGFloat = 6.0) {
        switch type {
        case .imageUpTitleDown:
            guard let imageSize = self.imageView?.image?.size,
                let text = self.titleLabel?.text,
                let font = self.titleLabel?.font else {
                    return
            }
            
            self.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: -imageSize.width, bottom: -(imageSize.height + spacing), right: 0.0)
            
            let labelString = NSString(string: text)
            let titleSize = labelString.size(withAttributes: [NSAttributedString.Key.font: font])
            self.imageEdgeInsets = UIEdgeInsets(top: -(titleSize.height + spacing), left: 0.0, bottom: 0.0, right: -titleSize.width)
            
            let edgeOffset = abs(titleSize.height - imageSize.height) / 2.0;
            self.contentEdgeInsets = UIEdgeInsets(top: edgeOffset, left: 0.0, bottom: edgeOffset, right: 0.0)
        default:
            break
        }
    }
}

  • Objective-C
/ the space between the image and text
CGFloat spacing = 6.0;

// lower the text and push it left so it appears centered 
//  below the image
CGSize imageSize = button.imageView.image.size;
button.titleEdgeInsets = UIEdgeInsetsMake(
  0.0, - imageSize.width, - (imageSize.height + spacing), 0.0);

// raise the image and push it right so it appears centered
//  above the text
CGSize titleSize = [button.titleLabel.text sizeWithAttributes:@{NSFontAttributeName: button.titleLabel.font}];
button.imageEdgeInsets = UIEdgeInsetsMake(
  - (titleSize.height + spacing), 0.0, 0.0, - titleSize.width);

// increase the content height to avoid clipping
CGFloat edgeOffset = fabsf(titleSize.height - imageSize.height) / 2.0;
button.contentEdgeInsets = UIEdgeInsetsMake(edgeOffset, 0.0, edgeOffset, 0.0);

参考:

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,193评论 0 10
  • 上午很早就起来了,但是早饭吃的有点晚还挺烦躁的,毕竟我是一个从来不会饿着自己的人。但这也并不是能让我荒废时间的理由...
    蜜桃如歌阅读 1,148评论 0 0
  • 天天泡简书,虽然一直未更新,也断断续续在绘画,16年累却有所收获,新的一年愿一切更好。感觉自己在一点点慢慢进步,1...
    浅许安然阅读 2,929评论 0 0
  • #易效能时间管理100天践行#20170110(20/100) #易效能时间管理100讲分享#20讲 学习感悟: ...
    时间的天使阅读 2,615评论 0 0

友情链接更多精彩内容