在视图控制器中更新UIBarButtonItem

时间:2019-06-11 11:28:57

标签: ios objective-c uibarbuttonitem

我正在尝试从视图控制器更新UIBarButtonItem的颜色,但是没有任何变化。我们不能使用UIBarButtonItem在视图控制器中访问self.navigationItem.rightBarButtonItem吗?

[UIView animateWithDuration:.8 delay:0.5 options:UIViewAnimationOptionAllowUserInteraction animations:^ {
        //button.alpha = .01;  //don't animate alpha to 0, otherwise you won't be able to interact with it
        self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    } completion:^(BOOL finished) {
        self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    }];

3 个答案:

答案 0 :(得分:0)

我已经尝试通过制作UIBarButtonItem的插座来解决您的问题。一切正常。您可以通过直接参考来设置色调颜色。

这是代码

class ViewController: UIViewController {

@IBOutlet weak var addItem: UIBarButtonItem!
var  username = UITextField()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.


}

@IBAction func addItem(_ sender: UIBarButtonItem) {

    UIView.animate(withDuration: 20) {

        self.addItem.tintColor = UIColor.red
    }
}
}

答案 1 :(得分:0)

let addButton = UIButton(type: .custom)
addButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
addButton.tintColor = UIColor.gray
let addMoreItem = UIBarButtonItem(customView: addButton)
self.navigationItem.rightBarButtonItem = addMoreItem

可能对您有用。

答案 2 :(得分:0)

UIButton *btnBack = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
[btnback setTintColor:[UIColor whiteColor]];
[btnBack addTarget:self action:@selector(onClickBtnBack:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btnBack];
self.navigationItem.rightBarButtonItem = barButtonItem;

还可以设置背景颜色和文本颜色。