1. 程式人生 > >iOS實戰演練之封裝圖片在上文字在下的button以及相關問題

iOS實戰演練之封裝圖片在上文字在下的button以及相關問題

       廢話不多說,直接上程式碼:

封裝圖片在上文字在下

-(void)initButton:(UIButton*)btn{
    //使圖片和文字水平居中顯示
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    //文字距離上邊框的距離增加imageView的高度,距離左邊框減少imageView的寬度,距離下邊框和右邊框距離不變
    [btn setTitleEdgeInsets:UIEdgeInsetsMake(btn.imageView.frame.size.height
+50,-btn.imageView.frame.size.width, 0.0,0.0)]; //圖片距離右邊框距離減少圖片的寬度,其它不邊 [btn setImageEdgeInsets:UIEdgeInsetsMake(-30, 0.0,0.0, -btn.titleLabel.bounds.size.width)]; }

封裝整體的button

-(void)initButton:(UIButton *)btn image:(UIImage *)image title:(NSString *)title titleColor:(UIColor *)titleColor backgroundColor:(UIColor
*)bgColor { [btn setImage:image forState:UIControlStateNormal]; [btn setTitle:title forState:UIControlStateNormal]; [btn setTitleColor: titleColor forState:UIControlStateNormal]; [self initButton:btn]; btn.layer.cornerRadius = 4.5; btn.backgroundColor = bgColor; }

載入button

@interface SCCardReceiveAndSendViewController ()
@property (weak, nonatomic) IBOutlet UIButton *ReceiveBtn;
@property (weak, nonatomic) IBOutlet UIButton *SendBtn;

@end

@implementation SCCardReceiveAndSendViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initButton:_SendBtn image:[UIImage imageNamed:@"Send"] title:@"傳送名片" titleColor:[UIColor colorWithRed:0.334 green:0.231 blue:1.000 alpha:1.000] backgroundColor:[[UIColor colorWithRed:0.887 green:1.000 blue:0.237 alpha:1.000] colorWithAlphaComponent:0.8]];

    [self initButton:_ReceiveBtn image:[UIImage imageNamed:@"received2"] title:@"接受名片" titleColor:[UIColor colorWithRed:0.824 green:0.969 blue:1.000 alpha:1.000] backgroundColor:[[UIColor colorWithRed:0.065 green:1.000 blue:0.018 alpha:0.648] colorWithAlphaComponent:0.8]];

}

遭遇問題:

       button的image加載出來和文字一個顏色,並不是圖片本身的顏色。

解決方法:

這裡寫圖片描述

       由於是直接在storyboard裡面建立的button,其Type預設是system,其tintColor預設為藍色,所以導致問題發生。只需要把Type改為Custom即可。

最後效果:

這裡寫圖片描述