UIbutton的圖文混排很多人一直沒有弄清楚驯绎,如果有圖片和文字的正常情況下,系統(tǒng)是左圖片又文字的黎泣,我們是在這個(gè)基礎(chǔ)上調(diào)整圖片和文字的位置,負(fù)為遠(yuǎn)離中心缤谎,正為靠近中心抒倚。不可能通過封裝一個(gè)方法滿足所有人的需求,在理解它原理的基礎(chǔ)上坷澡,通過下面的方法進(jìn)行微調(diào)整托呕。
//例子:上圖片下文字
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0, 0, 44, 44);//寬度自己調(diào)整
[btn setImage:[UIImage imageNamed:@"圖片"] forState:UIControlStateNormal];
[btn setTitle:@"圖片" forState:UIControlStateNormal];
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;//使圖片和文字水平居中顯示
[btn setImageEdgeInsets:UIEdgeInsetsMake(-btn.imageView.frame.size.height, btn.imageView.frame.size.width,0, 0)];//圖片距離右邊框距離減少圖片的寬度
[btn setTitleEdgeInsets:UIEdgeInsetsMake(btn.imageView.frame.size.height,-btn.imageView.frame.size.width,0,-6)];//文字距離上邊框的距離增加imageView的高度,距離左邊框減少imageView的寬度频敛,距離下邊框和右邊框距離根據(jù)實(shí)際情況調(diào)整
蘋果文檔的描述镣陕,大家可以看看
//imageEdgeInsets
## Discussion
Use this property to resize and reposition the effective drawing rectangle for the button image. You can specify a different value for each of the four insets (top, left, bottom, right). A positive value shrinks, or insets, that edge—moving it closer to the center of the button. A negative value expands, or outsets, that edge. Use the UIEdgeInsetsMake function to construct a value for this property. The default value is UIEdgeInsetsZero.
This property is used only for positioning the image during layout. The button does not use this property to determine intrinsicContentSize and sizeThatFits:.
//titleEdgeInsets
## Discussion
Use this property to resize and reposition the effective drawing rectangle for the button title. You can specify a different value for each of the four insets (top, left, bottom, right). A positive value shrinks, or insets, that edge—moving it closer to the center of the button. A negative value expands, or outsets, that edge. Use the UIEdgeInsetsMake function to construct a value for this property. The default value is UIEdgeInsetsZero.
The insets you specify are applied to the title rectangle after that rectangle has been sized to fit the button’s text. Thus, positive inset values may actually clip the title text.
This property is used only for positioning the title during layout. The button does not use this property to determine intrinsicContentSize and sizeThatFits:.