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

// 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

上一篇:69. x 的平方根


下一篇:Linux下使用Kickstart自动化安装平台架构