左文字右图片的BarButtonItem

创建一个带文字和图片的BarButtonItem,默认是图左文字右,但是想要的效果是文字左图右,下边定义一个创建button方法:

// 创建一个带文字和图片的BarButtonItem
- (UIButton *)creatBarButtonItemWithLeftTitleAndRightImage {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    
    // 设置图片
    UIImage *buttonImage = [UIImage imageNamed:@"SetPassword"];
    [button setImage:buttonImage forState:UIControlStateNormal];
    
    // 设置文字
    NSString *buttonTitleStr = @"竞猜明细";
    [button setTitle:buttonTitleStr forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:15];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    // 文本尺寸
    CGSize buttonTitleLabelSize = [buttonTitleStr sizeWithAttributes:@{NSFontAttributeName:button.titleLabel.font}];
    // 图片尺寸
    CGSize buttonImageSize = buttonImage.size;
    
    // Button默认图左文字右,但是设置TitleEdgeInsets和ImageEdgeInsets可以改变它们的位置关系(不加下边两行就是默认图左文字右)
    [button setTitleEdgeInsets:UIEdgeInsetsMake(0, -buttonImage.size.width, 0, buttonImage.size.width)];
    [button setImageEdgeInsets:UIEdgeInsetsMake(0, buttonTitleLabelSize.width, 0, -buttonTitleLabelSize.width)];
    
    button.frame = CGRectMake(0, 0, buttonImageSize.width + buttonTitleLabelSize.width, buttonImageSize.height);
    
    [button addTarget:self action:@selector(showPopupMenu) forControlEvents:UIControlEventTouchUpInside];
    
    return button;
}

在调用的地方进行如下调用即可:

 UIBarButtonItem *rightBBi = [[UIBarButtonItem alloc]initWithCustomView:[self creatBarButtonItemWithLeftTitleAndRightImage]];
 self.navigationItem.rightBarButtonItem = rightBBi;

你可能感兴趣的:(左文字右图片的BarButtonItem)