在使用UIButton的時候,大家對setImageEdgeInsets、setTitleEdgeInsets、setContentEdgeInsets了解嗎??
以前寫代碼如果單獨只有一個的話,用著也不用那么費事,一般設置也都是文字居中,或者圖片居中。這些系統都為你自動計算好了,而且擺放好了位置。
復雜一點的話,文字居左或者居右:contentHorizontalAlignment 這個屬性可以滿足大家的需求。
如果Image和title同時存在呢?或者現在需要:有個圖片和文字的Button或者View。最開始的時候我一般都是設個UIButton然后放上去一個ImageView和UILabel,是不是太遜了。o(╯□╰)o
以前對UIButton的三個EdgeInsets感覺老是摸不著邊,其實總結一句話:UIButton 中的內容都是默認居中,設置EdgeInsets之后還是居中。
詳解:
一:只設置Image
沒有設置setImageEdgeInsets
然后設置setImageEdgeInsets之后通過Debug View 查看ImageView的frame,得到數據:(Unbutton的Width都為335,圖片的Size為(32,32))
ImageView.x ? ? ? ? ? ?ImageEdgeInsets ? ? ? ? ? ? ? ? ? ? ? ?x得到的規則
151.5 ? ? ? ? ? ? ? ? ? ? ? (0, 0, 0, 0) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?(335 - 32 )/ 2
156.5 ? ? ? ? ? ? ? ? ? ? ? (0, 10, 0, 0) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?(335 - 32 - 10 )/ 2 + 10
101.5? ? ? ? ? ? ? ? ? ? ?? (0, 0, 0, 100) ? ? ? ? ? ? ? ? ? ? ? ? ? ? (335 - 32 - 100 )/ 2 + 0
106.5? ? ? ? ? ? ? ? ? ? ?? (0, 10, 0, 100) ? ? ? ? ? ? ? ? ? ? ? ? ? (335 - 32 - 10 - 100 )/ 2 + 10
是不是發現規律了,就是(button的寬度 - 離左右的距離 - 圖片的寬度)/ 2 + 離左邊的距離。所以還是居中嘍。
只有title的自己可以試試哈。
二:既設置Image,又設置title
沒有設置任何EdgeInsets
然后設置setImageEdgeInsets、setTitleEdgeInsets之后通過Debug View 查看ImageView的frame,得到數據:(Unbutton的Width都為335,圖片的Size為(32,32))
UIButton *tempButton = [UIButton buttonWithType:UIButtonTypeCustom];
tempButton.frame = CM(20, 100, Screen_Width - 40, 40);
tempButton.backgroundColor = OrangeColor;
[tempButton setTitle:@"秀美甲" forState:UIControlStateNormal];
[tempButton setImage:[UIImage imageNamed:@"first_selected"] forState:UIControlStateNormal];
tempButton.imageView.backgroundColor = RedColor;
[self.view addSubview:tempButton];
ImageView.x ? ?Label.frame ? ? ? ? ?ImageEdgeInsets ? ? ?TitleEdgeInsets ?
124.5? ? ? ? ? (156.5,9.5,54,21.5) ? ? ?(0,0,0,0) ? ? ? ? ? ? ? ? ? (0,0,0,0)
149.5? ? ? ? ? (156.5,9.5,54,21.5)? ? ? (0,50,0,0) ? ? ? ? ? ? ? ? (0,0,0,0)
149.5? ? ? ? ? (106.5,9.5,54,21.5)? ? ? (0,50,0,0) ? ? ? ? ? ? ? ? (0,0,0,100)
ImageView.x的計算規則有一點變化了:(button的寬度 - 離左右的距離 - 圖片的寬度 -Label的寬度)/ 2 + 離左邊的距離。
Label.x 的計算規則:(button的寬度 - 離左右的距離 - 圖片的寬度 -Label的寬度)/ 2 + 離左邊的距離 + 圖片的寬度。(默認左邊總有你設置的圖片似得)
既有圖片又有title的話,計算居中時總是以他倆的寬度為一體的。所以也是居中
三:在第二種的基礎上,再設置setContentEdgeInsets
ImageView.x ? ? ? ? ? ? ? ?Label.frame ? ? ? ? ? ? ?setContentEdgeInsets
134.5? ? ? ? ? ? ? ? ? ? (166.5, 9.5, 54, 21.5) ? ? ? ? ?(0, 20, 0, 0)
這個就是在原有的基礎上相當于把button的Width - 離左右邊的距離,之后再計算Image和Label的位置。
總之:還是居中。
注意:圖片的實際坐標 = 圖片的實際寬高/scale,scale由手機屏幕決定
http://www.lxweimin.com/p/16b9877374ab