iOS 对UIButton的imageView和titleLabel进行重新布局

iOS  对UIButton的imageView和titleLabel进行重新布局

#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(, , , );
//注意:在此不能使用[btn setBackgroundImage:[UIImage imageNamed:@"label_comment@3x"] forState:0],否则达不到想要的效果
[btn setImage:[UIImage imageNamed:@"label_comment@3x"] forState:];
[btn setTitle:@"哈哈" forState:];
[btn setTitleColor:[UIColor blackColor] forState:];
[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, ,imgWidth, imgHeight);
//titleLabel的尺寸
self.titleLabel.frame = CGRectMake(, self.bounds.size.height*LFButtonScale, self.bounds.size.width, self.bounds.size.height*(-LFButtonScale));
self.titleLabel.textAlignment = NSTextAlignmentCenter;
} @end
上一篇:关于如何用php 获取当前脚本的url


下一篇:cocos2d-x 实现沙子特效