程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> ios-如何在所有使用了自定義UINavigationBar的界面中使用自定義的UIBarButtonItem

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

編輯:編程綜合問答
如何在所有使用了自定義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];

能不能有一個統一的方法統一設置?

最佳回答:


你可以把這個加到一個單獨的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中也需要用到。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved