#import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
#import "AppDelegate.h" #import "RootViewController.h" @interface AppDelegate () @end @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]; self.window.rootViewController = [[RootViewController alloc] init]; [self.window makeKeyAndVisible]; return YES; } @end
#import <UIKit/UIKit.h> @interface RootViewController : UIViewController @end
#import "RootViewController.h" #import "LFCustomButton.h" @interface RootViewController () @end @implementation RootViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor greenColor]; LFCustomButton *btn = [LFCustomButton buttonWithType:UIButtonTypeCustom]; btn.frame = CGRectMake(100, 100, 100, 100); //注意:在此不能使用[btn setBackgroundImage:[UIImage imageNamed:@"label_comment@3x"] forState:0],否则达不到想要的效果 [btn setImage:[UIImage imageNamed:@"label_comment@3x"] forState:0]; [btn setTitle:@"哈哈" forState:0]; [btn setTitleColor:[UIColor blackColor] forState:0]; [self.view addSubview:btn]; } @end
#import <UIKit/UIKit.h> @interface LFCustomButton : UIButton @end
#import "LFCustomButton.h" const double LFButtonScale = 0.7; @implementation LFCustomButton /** * 在layoutSubviews中修改布局 */ - (void)layoutSubviews{ [super layoutSubviews]; //计算宽高 float imgHeight = MIN(self.bounds.size.width, self.bounds.size.height*LFButtonScale); float imgWidth = imgHeight; //imageView的尺寸 self.imageView.frame = CGRectMake((self.bounds.size.width - imgWidth)/2.0, 0,imgWidth, imgHeight); //titleLabel的尺寸 self.titleLabel.frame = CGRectMake(0, self.bounds.size.height*LFButtonScale, self.bounds.size.width, self.bounds.size.height*(1-LFButtonScale)); self.titleLabel.textAlignment = NSTextAlignmentCenter; } @end