标签:
UIButton的竖排图片和文本第一想法:实现思路第二种方法UIContentHorizontalAlignment/UIControlContentVerticalAlignment完整代码片段:参考资料:
UIButton的竖排的话,如果不知道方法,就会走很多弯路了
橙色-> 按钮frame
紫色->图片frame
绿色->文本frame
正常情况下,如果有图片,有文本,在 按钮宽度 > 图片宽度+文字宽度的情况下,按钮的frame布局是图1所示.
然而我们需要实现的是图4的效果.
如果将开始状态和结束状态重叠,如图2.此时,按照图2的图片frame的改变,文本的frame的改变来计算,你有可能会计算正确,当前也有可能计算不正确,这取决于iOS系统的心情,哈哈.
可以看看这两个属性:
The horizontal alignment of content (text or image) within the receive
The vertical alignment of content (text and images) within a control.
(from: xcdoc://?url=developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIControl_Class/index.html )
在头文件中也有这两个属性的说明:
@property(nonatomic) UIControlContentVerticalAlignment contentVerticalAlignment; // how to position content vertically inside control. default is center
@property(nonatomic) UIControlContentHorizontalAlignment contentHorizontalAlignment; // how to position content hozontally inside control. default is center
(from UIKit/UIControl.h)
从这里可以看到,这两个属性默认的值是center,也就是说:
控件内部的元素的排列方式是:水平方向居中,垂直方向居中
也就是图1的效果:
但是,如果我们将这两个属性都设置为左对齐,
[button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[button setContentVerticalAlignment:UIControlContentVerticalAlignmentTop];
此时,这两个按钮的位置就是图2的效果了.
好了,这个时候,要想从图3的状态转换到图4的状态就不是难事了.
xxxxxxxxxx
[button setImageEdgeInsets:UIEdgeInsetsMake(imageTopGap,//图片距离顶部距离
(buttonWidth-image.size.width)/2,//图片向右偏移距离
0,
0)];
[button setTitleEdgeInsets:UIEdgeInsetsMake((image.size.height + imageTopGap) + textTopGap, //图片底部+文字与图片间距
(buttonWidth - textWidth)/2 - image.size.width, //文字向右偏移距离
0,
0 )];
CGFloat buttonWidth = 80;
CGFloat buttonHeight = 80;
CGFloat textWidth = 40;
CGFloat imageTopGap = 10;
CGFloat textTopGap = 10;
[self.nomorlButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[self.nomorlButton setContentVerticalAlignment:UIControlContentVerticalAlignmentTop];
?
[self.nomorlButton setImageEdgeInsets:UIEdgeInsetsMake(imageTopGap,//图片距离顶部距离
(buttonWidth-image.size.width)/2,//图片向右偏移距离
0, 0)];
[self.nomorlButton setTitleEdgeInsets:UIEdgeInsetsMake((image.size.height + imageTopGap) + textTopGap, //图片底部+文字与图片间距
(buttonWidth - textWidth)/2 - image.size.width, //文字向右偏移距离
0,
0 )];
标签:
原文地址:http://www.cnblogs.com/xilifeng/p/4827808.html