UIbutton的圖文混排很多人一直沒有弄清楚,如果有圖片和文字的正常情況下,系統是左圖片又文字的,我們是在這個基礎上調整圖片和文字的位置,負為遠離中心,正為靠近中心。不可能通過封裝一個方法滿足所有人的需求,在理解它原理的基礎上,通過下面的方法進行微調整。
//例子:上圖片下文字
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0, 0, 44, 44);//寬度自己調整
[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的寬度,距離下邊框和右邊框距離根據實際情況調整
蘋果文檔的描述,大家可以看看
//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:.