设置UIButton图片和文字的位置(下上文图, 上图下文, 左
各位码友, 想必大家在项目中都会遇到这种场景, UI设计师设计一个按钮,非要同时有图片及文字,而且位置不一, 看到这里就有些头疼,今天来分享一个封装的api方法, 直接调用皆可简单实现其功能:
首先定义几个位置类型:
#pragma mark - button文字所在位置typedefNS_ENUM(NSInteger, RSButtonType) {
RSButtonTypeRight =0,
RSButtonTypeLeft,
RSButtonTypeBottom,
RSButtonTypeTop
};
我是在类的延展里写的,大家也可以采取其他方式写, 方法都是一样的~~
在.h文件中定义一个方法:
/**
* 设置button中title的位置
* *@paramtype type位置类型
*/
- (void)setButtonShowType:(RSButtonType)type;
然后在.m中实现该方法
- (void)setButtonShowType:(RSButtonType)type
{
[self layoutIfNeeded];CGRect titleFrame = self.titleLabel.frame;CGRect imageFrame = self.imageView.frame;CGFloat space = titleFrame.origin.x- imageFrame.origin.x- imageFrame.size.width+4;switch (type) {
case RSButtonTypeRight:
{
[self setTitleEdgeInsets:UIEdgeInsetsMake(0,imageFrame.size.width- space,0, -(imageFrame.size.width- space))];[self setImageEdgeInsets:UIEdgeInsetsMake(0, -(titleFrame.origin.x- imageFrame.origin.x),0, imageFrame.origin.x- titleFrame.origin.x)];}break;case RSButtonTypeLeft:
{
[self setImageEdgeInsets:UIEdgeInsetsMake(0,titleFrame.size.width+ space,0, -(titleFrame.size.width+ space))];[self setTitleEdgeInsets:UIEdgeInsetsMake(0, -(titleFrame.origin.x- imageFrame.origin.x),0, titleFrame.origin.x- imageFrame.origin.x)];}break;case RSButtonTypeBottom:
{
[self setImageEdgeInsets:UIEdgeInsetsMake(0,0, titleFrame.size.height+ space, -(titleFrame.size.width))];[self setTitleEdgeInsets:UIEdgeInsetsMake(imageFrame.size.height+ space, -(imageFrame.size.width),0,0)];}break;case RSButtonTypeTop:
{
[self setTitleEdgeInsets:UIEdgeInsetsMake(0,-(imageFrame.size.width), imageFrame.size.height+ space,0)];[self setImageEdgeInsets:UIEdgeInsetsMake(titleFrame.size.height+ space,(titleFrame.size.width),0,0)];}break;default:break;}
}
至于调用, 就更简单了
[_likeButton setButtonShowType:RSButtonTypeLeft];
效果如下图:
希望可以帮到大家, 发现错误欢迎及时指正, 共同进度!!!!