UIButton的图文混拍(竖直方向上的)
UIButton的的imageInset和titleLabelInset搞得我都吐了.
先上代码
UIButton *btAccount = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 104, 64)]; [btAccount setBackgroundColor:[UIColor colorWithRed:0.644 green:0.896 blue:1.000 alpha:1.000]]; UIImage *image = [UIImage imageNamed:@"1111"]; [btAccount setImage:image forState:UIControlStateNormal]; [btAccount setTitle:@"菜单" forState:UIControlStateNormal]; [btAccount setTitleColor:[UIColor colorWithRed:0.722 green:1.000 blue:0.450 alpha:1.000] forState:UIControlStateNormal]; CGSize strSize = [@"菜单" sizeWithAttributes:@{NSFontAttributeName:btAccount.titleLabel.font}]; [self.view addSubview:btAccount]; CGFloat spacing = 5.0; [btAccount setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft]; [btAccount setContentVerticalAlignment:UIControlContentVerticalAlignmentTop]; [btAccount setImageEdgeInsets:UIEdgeInsetsMake(0, (CGRectGetWidth(btAccount.frame) - image.size.width)/2.0, 0, 0)]; [btAccount setTitleEdgeInsets:UIEdgeInsetsMake(spacing + image.size.height, (CGRectGetWidth(btAccount.frame) - strSize.width)/2.0 - image.size.width, 0, 0)];
这里面是先将button的水平和竖直方向上设在左上角, 这样的话image和titleLabel就都会出现在button的左上角,
[btAccount setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft]; [btAccount setContentVerticalAlignment:UIControlContentVerticalAlignmentTop];
然后图片的话只需要向右移动就行了,
(CGRectGetWidth(btAccount.frame) - image.size.width)/2.0
titleLabel向下移动spacing+图片的高度, 向右移动
(CGRectGetWidth(btAccount.frame) - strSize.width)/2.0 - image.size.width