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

iOS 小技巧:調整 UIButton 中 title 與 image 的位置

編輯:iOS 開發綜合

UIButton 內的圖片與文字預設是「圖左文右」且緊緊相連,視覺上常常不理想。想要讓文字左移、圖片右移,其實只需要調整兩個 edge insets 屬性即可,無須自訂子類或重寫 layoutSubviews。

/**
 * 重新配置 UIButton 的版面
 *
 * @param button 需要調整的 UIButton
 */
- (void)layoutBtnWithBtn:(UIButton *)button {
    button.titleLabel.backgroundColor = button.backgroundColor;
    button.imageView.backgroundColor = button.backgroundColor;

    CGSize titleSize = button.titleLabel.bounds.size;
    CGSize imageSize = button.imageView.bounds.size;
    NSLog(@"titleSize: %@\nimageSize: %@",
          NSStringFromCGSize(titleSize), NSStringFromCGSize(imageSize));

    // 文字左移
    button.titleEdgeInsets = UIEdgeInsetsMake(0.0, -imageSize.width, 0.0, imageSize.width);

    // 圖片右移
    button.imageEdgeInsets = UIEdgeInsetsMake(0.0, titleSize.width, 0.0, -titleSize.width);
}

原理並不複雜:設定 title 與 image 之後,系統會自行計算文字與圖片的 frame,而 titleEdgeInsets 與 imageEdgeInsets 就是在這個基礎上再追加的位移量。把圖片的寬度從文字的左內距中扣除、加到文字的右內距,文字便往左挪;對圖片做反向處理,圖片便往右挪,兩者於是一左一右分開。

幾點實務提醒:

  • 這兩個屬性的數值必須在 titleLabel 與 imageView 尺寸確定之後才有意義,因此呼叫時機最好在 viewDidLayoutSubviews 或版面確定之後,避免在 viewDidLoad 中過早設定。
  • 位移量是相對的「內距調整」,並非絕對座標,改動字體或圖片尺寸後需要重新計算。
  • 若同時使用 Auto Layout 或 contentEdgeInsets,三者會疊加影響最終位置,需一併驗證。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved