iOS UIButton 左文字、右图片。上图片、下文字

/*左文字、右图片*/
- (UIButton *)screeningBtn {
    if (!_screeningBtn) {
        _screeningBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _screeningBtn.frame = CGRectMake(kScreenWidth - kW(15) - kW(48), kH(6),kW(48), kH(40));
        [_screeningBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_screeningBtn setTitle:@"筛选" forState:UIControlStateNormal];
        _screeningBtn.titleLabel.font = [UIFont systemFontOfSize:14.0];
        [_screeningBtn setImage:[UIImage imageNamed:@"nft_main_screening"] forState:UIControlStateNormal];
        [_screeningBtn addTarget:self action:@selector(p_screeningBtnClick) forControlEvents:UIControlEventTouchUpInside];
        /*左文字、右图片*/
        [_screeningBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, - _screeningBtn.imageView.image.size.width, 0, _screeningBtn.imageView.image.size.width)];
        [_screeningBtn setImageEdgeInsets:UIEdgeInsetsMake(0, _screeningBtn.titleLabel.bounds.size.width, 0, -_screeningBtn.titleLabel.bounds.size.width)];
    }
    return _screeningBtn;
}
/*将按钮设置为图片在上,文字在下*/
- (void)initButton:(UIButton*)btn {
    float  spacing = 4;//图片和文字的上下间距
    CGSize imageSize = btn.imageView.frame.size;
    CGSize titleSize = btn.titleLabel.frame.size;
    CGSize textSize = [btn.titleLabel.text sizeWithAttributes:@{NSFontAttributeName : btn.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 + spacing);
    btn.imageEdgeInsets = UIEdgeInsetsMake(- (totalHeight - imageSize.height), 0.0, 0.0, - titleSize.width);
    btn.titleEdgeInsets = UIEdgeInsetsMake(0, - imageSize.width, - (totalHeight - titleSize.height), 0);
}

你可能感兴趣的:(iOS UIButton 左文字、右图片。上图片、下文字)