2 summericeredtea summerICEREDTEA 于 2013.02.03 14:48 提问

如何在所有使用了自定义UINavigationBar的界面中使用自定义的UIBarButtonItem

不是每个界面都写一遍

UIImage image = [UIImage imageNamed:imagePath];
UIButton
button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
[button setImage:image forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:highLightImagePath] forState:UIControlStateHighlighted];
[button addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];

能不能有一个统一的方法统一设置?

1个回答

xiaoxiaoaishang
xiaoxiaoaishang   2013.02.04 13:49
已采纳

你可以把这个加到一个单独的global-variables文件中,像这样:

GlobalVariable.h

+(UIBarButtonItem*)customButton;

GlobalVariable.m

+(UIBarButtonItem*)customButton{
    UIImage image = [UIImage imageNamed:imagePath];
    UIButton button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
    [button setImage:image forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:highLightImagePath] forState:UIControlStateHighlighted];
    [button addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* btn = [[UIBarButtonItem alloc] initWithCustomView:button];
    return btn;
}

然后,在你想要按钮出现的view中import GlobalVariable.h,然后调用

self.navigationItem.leftBarButtonItem = [GlobalVariable customButton];

你可以一直用这个 GlobalVariable,以防你在其他的variables中也需要用到。

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!