xib Button 上同时显示文字和图片的处理

最近比较闲,对之前踩过的坑做一个总结

为了实现这种类似的button,左边文字,右边图片,或者是左边图片,右边图片

  • 方法一:xib 设置属性

在xib button 上有个属性,Semantic,Force Right-to-Left ,Force Left-to-Right

Force Right-to-Left  是图片在右,文字在左,Force Left-to-Right 是正好相反。 

选中编辑button,切换到size inspector页面,默认情况下 content Insets、Title Insets、Image Insets三个的默认值都为0,

设置Title Insets 的右边距或者是Image Insets 的左边距,可以调节文字和图片之间的距离。

但是Semantic这个属性对ios8 是无效的,iOS8没记错的话应该都是图片在左,文字在右,查了相关文献,针对ios8解决的方法如下:

扫描二维码关注公众号,回复: 6174040 查看本文章
/**
 针对ios8 调整button 图片和文字的位置
 
 @param button 带文字和图片button
 @param offset 右边图片距文字的距离
 @return 调整后的button
 */
+ (UIButton *)adjustmentaImageAndTitleOfbtn:(UIButton *)button Offset:(CGFloat)offset;
+ (UIButton *)adjustmentaImageAndTitleOfbtn:(UIButton *)button Offset:(CGFloat)offset {
    NSString *version= [UIDevice currentDevice].systemVersion;
    if (version.doubleValue < 9.0) {
        button.titleEdgeInsets = UIEdgeInsetsMake(0, -button.imageView.frame.size.width, 0, button.imageView.frame.size.width + offset);
        button.imageEdgeInsets = UIEdgeInsetsMake(0, button.titleLabel.frame.size.width, 0, -button.titleLabel.frame.size.width);
    } else {
        
    }
    return button;
}
  • 方法二:还是xib 文字和图片边距设置

无需设置Semantic 这个属性,可以直接调节TitleLabel的右边距,给图像留出空间,然后把图像左边距调到titleLabel的宽度,图像就出现在titleLabel的右边了,但是这个方法有时候很难设置。

  • 方法三:代码实现
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setImage:[UIImage imageNamed:@"image"] forState:UIControlStateNormal];
[btn setTitle:@"title" forState:UIControlStateNormal];
[btn setTitleEdgeInsets:UIEdgeInsetsMake(0, - btn.imageView.image.size.width, 0, btn.imageView.image.size.width)];
[btn setImageEdgeInsets:UIEdgeInsetsMake(0, btn.titleLabel.bounds.size.width, 0, -btn.titleLabel.bounds.size.width)]

UIButton默认是左图片,右文字。并且在设置edge insets之前, 位置已经有了设定。所以设置title的edge insets,真实的作用是在原来的边距值基础上增加或减少某个间距,负值便是减少。以title为例,设置右边距增加图片宽度,就使得自己的右边界距离按钮的右边界多了图片的宽度,正好放下图片。此时,titleLabel变小了,而titleLabel的左边界还在原来的位置上,所以label的左边界距离按钮的左边界减少图片的宽度,label就和原来一样大了,而且左侧起始位置和图片的左侧起始位置相同了。

参考:https://blog.csdn.net/u014599371/article/details/80111211

ps:了解一下semantic 这个属性,是允许iOS知道视图是否被反转的规则,有多种选择:

Unspecified: 视图的默认值,当从左到右和从右到左的布局进行切换时,视图被翻转。

Playback: 表示播放控制的视图,如播放,倒带或快进按钮或播放头清洗器。在从左到右和从右到左的布局之间切换时,这些视图不会翻转。

Force Left-To_Right: 始终使用从左到右布局显示的视图。

Force Right-To-Left: 始终使用从右到左的布局显示的视图。

猜你喜欢

转载自blog.csdn.net/baihailing/article/details/86594600
今日推荐