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)];

你可能感兴趣的:(iOS UIButton图片和文字布局(左图右文字))