- (void)viewDidLoad {
[super viewDidLoad];
UIImage *buttonImage = [UIImage imageNamed:@"xl.png"];
CGFloat buttonImageViewWidth = 50;//CGImageGetWidth(buttonImage.CGImage);
CGFloat buttonImageViewHeight = 50;//CGImageGetHeight(buttonImage.CGImage);
if ([UIScreen mainScreen].scale == 2.0f) {
buttonImageViewWidth*=0.5f;
buttonImageViewHeight*=0.5f;
}
NSString *buttonTitle = @"笑脸呵呵呵";
UIFont *buttonTitleFont = [UIFont systemFontOfSize:17.0f];
CGSize buttonTitleLabelSize = [buttonTitle sizeWithFont:buttonTitleFont];
// button宽度,至少为imageView宽度与titleLabel宽度之和
CGFloat buttonWidth = buttonImageViewWidth + buttonTitleLabelSize.width;
// button高度,至少为imageView高度与titleLabel高度之和
CGFloat buttonHeight = buttonImageViewHeight +buttonTitleLabelSize.height;
UIButton *b = [[UIButton alloc] init];
[b setCenter:CGPointMake(160, 160)];
[b setBounds:CGRectMake(0, 0, buttonWidth, buttonHeight)];
[b.titleLabel setFont:buttonTitleFont];
[b setBackgroundColor:[UIColor redColor]];
[b setImage:buttonImage forState:UIControlStateNormal];
[b.imageView setBackgroundColor:[UIColor greenColor]];
[b setTitle:buttonTitle forState:UIControlStateNormal];
[b setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[b setTitleColor:[UIColor scrollViewTexturedBackgroundColor] forState:UIControlStateHighlighted];
[b.titleLabel setBackgroundColor:[UIColor whiteColor]];
[self.view addSubview:b];
CGPoint buttonBoundsCenter = CGPointMake(CGRectGetMidX(b.bounds), CGRectGetMidY(b.bounds));
// 找出imageView 最终的center
CGPoint endImageViewCenter = CGPointMake(buttonBoundsCenter.x,CGRectGetMidY(b.imageView.bounds));
// 找出titleLabel 最终的center
CGPoint endTitleLabelCenter = CGPointMake(buttonBoundsCenter.x, CGRectGetHeight(b.bounds)-CGRectGetMidY(b.titleLabel.bounds));
// 取得imageView最初的center
CGPoint startimageViewCenter = b.imageView.center;
// 取得titleLabel最初的center
CGPoint startTitleLabelCenter =b.titleLabel.center;
// 设置imageEdgelnsets
CGFloat imageEdgelnsetsTop = endImageViewCenter.y - startimageViewCenter.y;
CGFloat imageEdgelnsetsLeft = endImageViewCenter.x - startimageViewCenter.x;
CGFloat imageEdgelnsetsBottom = -imageEdgelnsetsTop;
CGFloat imageEdgelnsetRight = -imageEdgelnsetsLeft;
b.imageEdgeInsets = UIEdgeInsetsMake(imageEdgelnsetsTop, imageEdgelnsetsLeft, imageEdgelnsetsBottom, imageEdgelnsetRight);
// 设置titleEdgeInsets
CGFloat titleEdgelnsetsTop = endTitleLabelCenter.y -startTitleLabelCenter.y;
CGFloat titleEdgelnsetsLeft = endTitleLabelCenter.x - startTitleLabelCenter.x;
CGFloat titleEdgelnsetsBottom = -titleEdgelnsetsTop;
CGFloat titleEdgelnsetsRight = -titleEdgelnsetsLeft;
b.titleEdgeInsets = UIEdgeInsetsMake(titleEdgelnsetsTop, titleEdgelnsetsLeft, titleEdgelnsetsBottom, titleEdgelnsetsRight);
// Do any additional setup after loading the view, typically from a nib.
}