【问题标题】:How to add an image to UIBarButtonItem?如何将图像添加到 UIBarButtonItem?
【发布时间】:2011-07-17 04:03:15
【问题描述】:

我创建了一个自定义按钮并将其应用于 UIbarbuttonitem。 没有错误,但导航栏上没有显示任何内容:( 这是我的代码-

    //create a custom button
    UIImage *image = [UIImage imageNamed:@"TESTButton.png"];
    UIButton *myCustomButton = [UIButton buttonWithType:UIButtonTypeCustom];
    myCustomButton.bounds = CGRectMake( 0, 0, image.size.width, image.size.height );    
    [myCustomButton setImage:image forState:UIControlStateNormal];
    [myCustomButton addTarget:nil action:@selector(goBack:) forControlEvents:UIControlEventTouchUpInside];


    UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithCustomView:myCustomButton];
    self.navigationItem.leftBarButtonItem = button;
    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;

    [button release];
    [myCustomButton release];
    [image release];
    [navID release];

谁能修复我的代码? :)

【问题讨论】:

    标签: objective-c ios uibarbuttonitem navigationbar


    【解决方案1】:

    来自the docs:

    initWithImage:style:target:action:
    

    试试看。

    【讨论】:

    • 喜欢这个? UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStyleBordered target:self action:@selector(goBack:)];仍然无法正常工作..没有错误,但没有显示任何内容:(
    • 确保你的图片没有返回为 nil。
    【解决方案2】:

    要设置任何具有正确颜色的图像,请使用 UIButton,设置“状态图像”,然后使用 customView

    创建 UIBarButtonItem
    UIImage *btnImage = [UIImage imageNamed:@"button"];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.bounds = CGRectMake( 0, 0, btnImage.size.width, btnImage.size.height );
    [btn addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchDown];
    [btn setImage:btnImage forState:UIControlStateNormal];
    _buttonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    

    【讨论】:

      【解决方案3】:

      最简单的方法之一是:

      UIBarButtonItem *button2 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"backk.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backBtn:)];
      self.navigationItem.leftBarButtonItem = button2;
      

      动作方法:

      - (IBAction)backBtn:(id)sender
      {
          [self.navigationController popViewControllerAnimated:YES];
      }
      

      【讨论】:

        猜你喜欢
        • 2016-11-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-01
        • 1970-01-01
        • 2011-06-18
        相关资源
        最近更新 更多