UIToolbar UIBarButtonItem with both image and title has very dim text

前端 未结 3 828
情话喂你
情话喂你 2020-12-10 08:28

My iPhone view adds some custom buttons to its toolbar. Each button has both an image and textual title, and is created like this:

UIBarButtonItem *fooButton         


        
3条回答
  •  时光说笑
    2020-12-10 09:14

    The answers here are nice, however its often a little easier to use composition rather than inheritance with UIKit classes.

    Create a bar item like so:

    _accountBarItem =
        [[UIBarButtonItem alloc] initWithCustomView:[CustomerBarView buttonWithImage:
        [UIImage imageNamed:@"Account.png"] text:@"Account"]];
    [_accountBarItem setTarget:self];
    [_accountBarItem setAction:@selector(accountButtonPressed)];
    

    Implementation of Custom View with Image and Label

    @implementation CustomBarView
    
    + (instancetype)buttonWithImage:(UIImage*)image text:(NSString*)text
    {
        CustomBarView* button = [[CustomBarView alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
        [button setText:text];
        [button setImage:image];
        return button;
    }
    
    
    - (id)initWithFrame:(CGRect)frame
    {
        self = [super initWithFrame:frame];
        if (self)
        {
            _uiButton = [UIButton buttonWithType:UIButtonTypeCustom];
            [self addSubview:_uiButton];
    
            _label = [[UILabel alloc] initWithFrame:CGRectZero];
            [_label setTextColor:[UIColor whiteColor]];
            [_label setFont:[UIFont boldApplicationFontOfSize:9]];
            [_label setBackgroundColor:[UIColor clearColor]];
            [_label setTextAlignment:NSTextAlignmentCenter];
            [self addSubview:_label];
        }
        return self;
    }
    
    
    - (void)setText:(NSString*)text
    {
        [_label setText:text];
    }
    
    - (void)setImage:(UIImage*)image
    {
        [_uiButton setImage:image forState:UIControlStateNormal];
    }
    
    
    
    
    - (void)layoutSubviews
    {
        [super layoutSubviews];
        [_uiButton setFrame:self.bounds];
        [_label setFrame:CGRectMake(2, self.height - 13, self.width - 4, 15)];
    }
    
    @end
    

提交回复
热议问题