Setting a UIImage to a UIBarButton item

前端 未结 2 1739
有刺的猬
有刺的猬 2021-01-28 07:45

I can\'t seem to add an image to this UIBarButtonItem without it crashing when touched:

 UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@\"         


        
相关标签:
2条回答
  • 2021-01-28 07:58

    You have to set the buttonStyle to custom not a UIBarButtonItemStylePlain

    and then [barbuttonitem setCustomView:anImageView];

    0 讨论(0)
  • 2021-01-28 08:12

    To call

    self.navigationItem.leftBarButtonItem = [CustomBarButton createNavBackBarButtonItemWithTitle:NSLocalizedString(@"Back", @"") target:self action:@selector(actionBack:)];
    

    CustomBarButton has createNavBackBarButtonItemWithTitle class function

    +(UIBarButtonItem *)createNavBackBarButtonItemWithTitle:(NSString *)t target:(id)tgt action:(SEL)a
    {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    // Since the buttons can be any width we use a thin image with a stretchable center point
    UIImage *buttonImage = [[UIImage imageNamed:@"back_button_up.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:0];
    UIImage *buttonPressedImage = [[UIImage imageNamed:@"back_button_over.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:0];
    
    
    [[button titleLabel] setFont:[UIFont boldSystemFontOfSize:12.0]];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
    //[[button titleLabel] setShadowOffset:CGSizeMake(0.0, 1.0)];
    
    CGRect buttonFrame = [button frame];
    buttonFrame.size.width = [t sizeWithFont:[UIFont boldSystemFontOfSize:12.0]].width + 24.0;
    buttonFrame.size.height = buttonImage.size.height;
    [button setFrame:buttonFrame];
    
    [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
    [button setBackgroundImage:buttonPressedImage forState:UIControlStateHighlighted];
    
    [button setTitle:[NSString stringWithFormat:@"  %@",t] forState:UIControlStateNormal];
    
    [button addTarget:tgt action:a forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    
    return [buttonItem autorelease];
    }
    
    0 讨论(0)
提交回复
热议问题