UIButton图片与文字位置调整

时间:2021-08-21 23:47:12

1:左图右文

默认效果就行

 

2:左文右图

UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn addTarget:self action:@selector(changeBtnClicked) forControlEvents:UIControlEventTouchUpInside];
btn.frame = CGRectMake(0, 0, 80, 20);
btn.titleLabel.font = kNormalActionFont;
[btn setTitleColor:DJNavTextColor forState:UIControlStateNormal];

NSDictionary *cityDict = [QTXUserDataModel objectForDestKey:kUserLocationCityKey];
NSString *tStr = cityDict[@"city"];
UIImage *aImg = [UIImage imageNamed:@"btn_arrow_bottom"];
{
[btn setImage:aImg forState:UIControlStateNormal];
[btn setTitle:tStr forState:UIControlStateNormal];

btn.titleEdgeInsets = UIEdgeInsetsMake(0, -btn.imageView.frame.size.width, 0, btn.imageView.frame.size.width);
btn.imageEdgeInsets = UIEdgeInsetsMake(0, btn.titleLabel.frame.size.width, 0, -btn.titleLabel.frame.size.width);
}

  

 

3:上图下文

            UIButton *aBtn = [UIButton buttonWithType:UIButtonTypeCustom];

            aBtn.frame = CGRectMake((kCellWidth-90)/2, self.view.height - 20 - 45, 90, 45);

            [aBtn addTarget:self action:@selector(logoutBtnClicked) forControlEvents:UIControlEventTouchUpInside];

            aBtn.titleLabel.font = [UIFont systemFontOfSize:12.5];

            [aBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

            [aBtn setTitle:_(@"切换/退出账号") forState:UIControlStateNormal];

            [aBtn setImage:[UIImage imageNamed:@"icon_quit"] forState:UIControlStateNormal];

            [self.view addSubview:aBtn];

            

            CGSize imageSize = aBtn.imageView.frame.size;

            CGSize titleSize = aBtn.titleLabel.frame.size;

            CGSize textSize = [aBtn.titleLabel.text sizeWithFont:aBtn.titleLabel.font];

            CGSize frameSize = CGSizeMake(ceilf(textSize.width), ceilf(textSize.height));

            if (titleSize.width + 0.5 < frameSize.width) {

                titleSize.width = frameSize.width;

            }

            CGFloat totalHeight = (imageSize.height + titleSize.height + 5);

            aBtn.imageEdgeInsets = UIEdgeInsetsMake(- (totalHeight - imageSize.height), 0.0, 0.0, - titleSize.width);

            aBtn.titleEdgeInsets = UIEdgeInsetsMake(0, - imageSize.width, - (totalHeight - titleSize.height), 0);