iOS 创建特殊的按钮 图片和文字在不同的位置

平时开发根据需求需要创建特殊的按钮,图片在上文字在下,文字在上图片在下,文字在左图片在右.

        一个分类即可解决.创建按钮后调用一下 - (void)cz_makeSpecialButtonWithSpecialType:(CZSpecialButtonType)specialType Space:(CGFloat)space; 即可.

        代码如下:

space 图片和文字之间的距离.

#import

typedef NS_ENUM(NSUInteger, CZSpecialButtonType) {

    CZSpecialButtonType_Default =0,//默认图片在左文字在右

    CZSpecialButtonType_ImgUpTitleDown,//图上字下

    CZSpecialButtonType_imgRightTitleLeft,//图右字左

    CZSpecialButtonType_ImgDownTitleUp//图下字上

};

NS_ASSUME_NONNULL_BEGIN

@interfaceUIButton(SpecialButton)

/// 特殊按钮

/// @param specialType 文字和图片的位置

/// @param space图片和文字之间的距离

- (void)cz_makeSpecialButtonWithSpecialType:(CZSpecialButtonType)specialType Space:(CGFloat)space;

@end

NS_ASSUME_NONNULL_END

#import "UIButton+SpecialButton.h"

//#import

@implementationUIButton(SpecialButton)

- (void)cz_makeSpecialButtonWithSpecialType:(CZSpecialButtonType)specialType Space:(CGFloat)space {

    UIImage*img =self.imageView.image;

    NSString*title =self.titleLabel.text;


    CGFloatimgW = img.size.width;

    CGFloatimgH = img.size.height;

    UIFont*font =self.titleLabel.font;


    NSDictionary*atticDic =@{NSFontAttributeName:font};

    CGSizetitleSize = [titlesizeWithAttributes:atticDic];

    CGFloattitleW = titleSize.width;

    CGFloattitleH = titleSize.height;


    CGFloatselfW =self.bounds.size.width;

//    CGFloat selfH = self.bounds.size.height;


    if((titleW >= (selfW - imgW - space))) {

        titleW = selfW - imgW - space;

    }


    switch(specialType) {

        case CZSpecialButtonType_Default:{

            NSLog(@"按钮走了默认状态 ---- 0 ---- ");

            self.imageEdgeInsets=UIEdgeInsetsMake(0, -space/2.0,0, space/2.0);

            self.titleEdgeInsets=UIEdgeInsetsMake(0, space/2.0,0, -space/2.0);

        }

            break;

        case CZSpecialButtonType_imgRightTitleLeft:{

            self.imageEdgeInsets=UIEdgeInsetsMake(0, titleW + space/2.0,0, -(titleW + space/2.0));

            self.titleEdgeInsets=UIEdgeInsetsMake(0, -(imgW + space/2.0),0, imgW + space/2.0);

        }

            break;

        case CZSpecialButtonType_ImgDownTitleUp:{

                self.imageEdgeInsets=UIEdgeInsetsMake((imgH + space)/2.0, titleW/2.0, -(imgH+space)/2.0, -titleW/2.0);

                self.titleEdgeInsets=UIEdgeInsetsMake(-(titleH + space)/2.0, -imgW/2.0, (titleH + space)/2.0, imgW/2.0);

        }

            break;

        case CZSpecialButtonType_ImgUpTitleDown:{

                self.imageEdgeInsets=UIEdgeInsetsMake(-(imgH + space)/2.0, titleW/2.0, (imgH+space)/2.0, -titleW/2.0);

                self.titleEdgeInsets=UIEdgeInsetsMake((titleH + space)/2.0, -imgW/2.0, -(titleH + space)/2.0, imgW/2.0);

        }

            break;


        default:

            break;

    }


}

@end

你可能感兴趣的:(iOS 创建特殊的按钮 图片和文字在不同的位置)