您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 總結:讓 UIButton 同時顯示文字與圖片(圖文混排)

編輯:iOS 開發綜合

UIButton 雖然可以同時設定 title 與 image,但系統只會把圖片置中、文字放在下方,位置完全無法直接指定。要達到「圖在右、文字靠左填滿」這種設計稿常見的排版,必須覆寫兩個方法。

目標效果:

解法:繼承 UIButton 並覆寫兩個 Rect 方法

UIButton 內部會呼叫 titleRectForContentRect: 與 imageRectForContentRect: 來決定子元素的 frame。只要覆寫這兩個方法,就能完全掌控排版。

#import "yxpButton.h"

@implementation yxpButton

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // 可依需求自由調整
        self.titleLabel.textAlignment = NSTextAlignmentRight;
        self.titleLabel.font = [UIFont systemFontOfSize:14.0];
        self.imageView.contentMode = UIViewContentModeLeft;
    }
    return self;
}

// 依 button 的 contentRect 決定 title 的位置
- (CGRect)titleRectForContentRect:(CGRect)contentRect {
    CGFloat titleW = contentRect.size.width - 30;   // 右側留 30pt 給圖片
    CGFloat titleH = contentRect.size.height;
    return CGRectMake(0, 0, titleW, titleH);
}

// 依 button 的 contentRect 決定 imageView 的位置
- (CGRect)imageRectForContentRect:(CGRect)contentRect {
    CGFloat imageW = 25;
    CGFloat imageH = 25;
    CGFloat imageX = contentRect.size.width - 26;
    CGFloat imageY = 2.5;
    return CGRectMake(imageX, imageY, imageW, imageH);
}

@end

使用方式

yxpButton *selectAreaButton =
    [[yxpButton alloc] initWithFrame:CGRectMake(200, 5, 100, 30)];
[selectAreaButton setTitle:@"圖文混排" forState:UIControlStateNormal];
[selectAreaButton setImage:[UIImage imageNamed:@"location"] forState:UIControlStateNormal];
[selectAreaButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[navigationBgView addSubview:selectAreaButton];

為什麼這樣可行

這兩個方法的參數 contentRect,是扣掉 contentEdgeInsets 之後的可用區域。你回傳什麼,系統就把 title 或 image 擺在那裡。範例中的數字(30、26、2.5)是硬編碼,實務上建議改用比例計算,例如:

- (CGRect)imageRectForContentRect:(CGRect)contentRect {
    CGFloat imageW = 16;
    return CGRectMake(contentRect.size.width - imageW - 4,
                      (contentRect.size.height - imageW) / 2.0,
                      imageW, imageW);
}

這樣換不同高度的按鈕時,圖片仍會垂直居中。

其他做法比較

  • 設定 imageEdgeInsets 與 titleEdgeInsets:不必建立子類,但兩個 inset 會互相影響,微調時容易越弄越亂。
  • 覆寫這兩個 Rect 方法:最可控,建議做法。
  • iOS 15 的 UIBadgeConfiguration / UIButtonConfiguration:若使用 iOS 15 以上,UIButtonConfiguration 內建 imagePadding 與 imagePlacement(.trailing 就是圖在右),一行設定即可,不必再繼承。
  • 自繪:直接用 UILabel + UIImageView 放進 UIView,加上 UITapGestureRecognizer。自由度最高,但失去 UIButton 的狀態管理與無障礙支援。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved