UIButton中,如果文字和圖片都同時存在的話,系統(tǒng)默認圖片在左邊,文字在右邊,有些UI需求是圖片在右邊,文字在左邊,這就需要用代碼調(diào)試,使UIButton中兩個元素的位置發(fā)生交換。
設(shè)置UIButton的兩個屬性可以達到交換的目的,這兩個屬性是titleEdgeInsets和imageEdgeInsets.
UIEdgeInsets為一個結(jié)構(gòu)體
typedef struct UIEdgeInsets { CGFloat top, left, bottom, right; } UIEdgeInsets;
這個結(jié)構(gòu)體表示上,左,下,右的偏移量,
top : 為正數(shù)的時候,是往下偏移,為負數(shù)的時候往上偏移;
left : 為正數(shù)的時候往右偏移,為負數(shù)的時候往左偏移;
bottom : 為正數(shù)的時候往上偏移,為負數(shù)的時候往下偏移;
right:為正數(shù)的時候往左偏移,為負數(shù)的時候往右偏移;
兩個元素,文字和圖片交換的第一步,要取得這兩個元素的寬度值
CGFloat labelWidth = button.titleLabel.intrinsicContentSize.width; //注意不能直接使用titleLabel.frame.size.width,原因為有時候獲取到0值CGFloat imageWidth = button.imageView.frame.size.width;CGFloat space = 8.f; //定義兩個元素交換后的間距
第二步設(shè)置button偏移量屬性
button.titleEdgeInsets = UIEdgeInsetsMake(0, - imageWidth - space,0,imageWidth + space);
button.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth + space, 0, -labelWidth - space);