首页 热点资讯 义务教育 高等教育 出国留学 考研考公
您的当前位置:首页正文

UIbutton 上图片下文字

2024-12-20 来源:化拓教育网

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:.

显示全文