各位碼友, 想必大家在項(xiàng)目中都會(huì)遇到這種場(chǎng)景寞酿, UI設(shè)計(jì)師設(shè)計(jì)一個(gè)按鈕家夺,非要同時(shí)有圖片及文字,而且位置不一伐弹, 看到這里就有些頭疼拉馋,今天來(lái)分享一個(gè)封裝的api方法, 直接調(diào)用皆可簡(jiǎn)單實(shí)現(xiàn)其功能:
首先定義幾個(gè)位置類(lèi)型:
#pragma mark - button文字所在位置typedefNS_ENUM(NSInteger, RSButtonType) {
RSButtonTypeRight =0,
RSButtonTypeLeft,
RSButtonTypeBottom,
RSButtonTypeTop
};
我是在類(lèi)的延展里寫(xiě)的惨好,大家也可以采取其他方式寫(xiě)煌茴, 方法都是一樣的~~
在.h文件中定義一個(gè)方法:
/**?
* ?設(shè)置button中title的位置
* *@paramtype type位置類(lèi)型
?*/
- (void)setButtonShowType:(RSButtonType)type;
然后在.m中實(shí)現(xiàn)該方法
- (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;}
}
至于調(diào)用, 就更簡(jiǎn)單了
[_likeButton setButtonShowType:RSButtonTypeLeft];
效果如下圖:
希望可以幫到大家日川, 發(fā)現(xiàn)錯(cuò)誤歡迎及時(shí)指正蔓腐, 共同進(jìn)度!A渚洹;芈邸!