0

如何在所有使用自定义 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];

很多界面backBarButtonItem需要自定义,代码都一样,不想写N遍

4

1 回答 1

0

您可以将其添加到单例全局变量文件中,例如

全局变量.h

+(UIBarButtonItem*)customButton;

全局变量.m

+(UIBarButtonItem*)customButton{
    UIImage *image = [UIImage imageNamed:imagePath];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(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;
}

GlobalVariable.h然后,在您希望按钮出现的视图中导入并调用

self.navigationItem.leftBarButtonItem = [GlobalVariable customButton];

您可以将 GlobalVariable 保留在那里,以防您还需要其他变量。

于 2013-02-03T10:37:12.957 回答