代码改变世界

iOS 自定义UIButton(图片和文字混合)

2015-06-22 23:00  甘雨路  阅读(1315)  评论(0编辑  收藏  举报

 // UIApplicationDelegate  .h文件

#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@end

 

 // UIApplicationDelegate  .m文件

 

#import "AppDelegate.h"

#import "CustomButton.h"

@implementation AppDelegate

 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    // Override point for customization after application launch.

    self.window.backgroundColor = [UIColor whiteColor];

  

    CustomButton *customBtn = [[CustomButton alloc] init];

    customBtn.frame = CGRectMake(100,150, 150, 60);

    [customBtn setTitle:@"十二年" forState:0];

    [customBtn setImage:[UIImage imageNamed:@"De.png"] forState:0];

    [self.window addSubview:customBtn];

 

    [self.window makeKeyAndVisible];

    return YES;

}

@end

 

 

// 自定义CustomButton类,继承UIButton

// CustomButton .h文件

 

#import <UIKit/UIKit.h>

@interface CustomButton : UIButton

@end

 

 

 

 

// CustomButton  .m文件

 

#import "CustomButton.h"

 

 

 

@implementation CustomButton

 

 

 

 

 

-(id)initWithFrame:(CGRect)frame

 

{

 

    self = [super initWithFrame:frame];

 

    if (self) {

 

        //设置粗体文字,以及文字的大小

 

        self.titleLabel.font = [UIFont boldSystemFontOfSize:20];

 

        // 设置文字居右

 

        self.titleLabel.textAlignment = NSTextAlignmentRight;

 

        // 设置文字的颜色

 

        [self setTitleColor:[UIColor redColor] forState:0];

 

        // 设置背景图片

 

        self.backgroundColor = [UIColor greenColor];

 

    }

 

    return self;

 

}

 

- (CGRect)titleRectForContentRect:(CGRect)contentRect

 

{

 

    CGRect titleFrame = CGRectMake(0, 0, contentRect.size.width * 0.6, contentRect.size.height);

 

    return titleFrame;

 

}

 

 

- (CGRect)imageRectForContentRect:(CGRect)contentRect

 

{

 

    return CGRectMake(contentRect.size.width * 0.6, 0, contentRect.size.width * 0.4, contentRect.size.height);

 

}

 

@end