iOS UIButton图片和文字布局(左图右文字)

        _leftBarBtn = [UIButton buttonWithType:(UIButtonTypeSystem)];
        [_leftBarBtn setImage:[UIImage imageNamed:@"downArrow"] forState:(UIControlStateNormal)];
        [_leftBarBtn setTitle:@"北京6" forState:(UIControlStateNormal)];
        [_leftBarBtn addTarget:self action:@selector(leftBarBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
        [_leftBarBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        [_leftBarBtn.titleLabel setFont:[UIFont systemFontOfSize:15.f]];
        
        //图片的大小必须是实际大小
        CGFloat imageWidth = 10.f;
        CGFloat spacing = 5.f;
        CGSize size = [@"北京" boundingRectWithSize:CGSizeMake(0, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:15.f]} context:nil].size;
        _leftBarBtn.frame = CGRectMake(0, 0, size.width + imageWidth + spacing, 30.f);
        
        CGFloat width = _leftBarBtn.frame.size.width;
        CGFloat height = _leftBarBtn.frame.size.height;
        [_leftBarBtn setImageEdgeInsets:UIEdgeInsetsMake((height - imageWidth) / 2, width - imageWidth, (height - imageWidth) / 2, 0)];
        [_leftBarBtn setTitleEdgeInsets:UIEdgeInsetsMake((height - size.height) / 2, -imageWidth-spacing, (height - size.height) / 2, imageWidth)];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容