2016-05-03 92 views
0

我想有一個大的加號按鈕的右邊欄按鈕,下面的代碼工作,而這是在故事板,但一切都移動到廈門國際銀行文件和獨立.swift文件後,這是唯一打破的。添加自定義的UIBarButtonItem到UINavigationBar的

let button = UIButton(type: .Custom) 
button.setTitle("+", forState: .Normal) 
button.titleLabel?.font = UIFont.systemFontOfSize(20.0) 
button.frame = CGRectMake(0, 0, 100, 40) 
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button) 
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "+", style: .Plain, target: self, action: #selector(GroupNavViewController.onCreate)) 
self.navigationItem.rightBarButtonItem?.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFontOfSize(40)], forState: .Normal) 

UINavigationController是它自己的.swift文件,沒有xib文件。

我不明白它爲什麼在故事板中起作用,但現在不行。

理想情況下,我想有一個大的加號按鈕(爲正常字體大小似乎有點太小)

+0

你是怎麼把在廈門國際銀行文件?導航欄? – MudOnTire

+0

導航控制器包含另一個視圖控制器,但本身沒有xib文件。 https://github.com/gomeow/BillSplitter/blob/master/BillSplitter/GroupNavViewController.swift#L20-L26 –

回答

1

確實對我有用。我剛剛擺脫了目標行動,所以我不必執行它。全部以代碼完成。沒有故事板和沒有xibs。

AppDelegate.swift

var window: UIWindow? 
let viewController = ViewController(); 

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 

    let navigationController = UINavigationController(rootViewController:viewController) 

    self.window = UIWindow(frame: UIScreen.mainScreen().bounds) 
    self.window!.backgroundColor = UIColor.whiteColor() 
    self.window!.rootViewController = navigationController 
    self.window!.makeKeyAndVisible() 

    return true 
} 

ViewController.swift

override func viewDidLoad() { 
    super.viewDidLoad() 

    let button = UIButton(type: .Custom) 
    button.setTitle("+", forState: .Normal) 
    button.titleLabel?.font = UIFont.systemFontOfSize(20.0) 
    button.frame = CGRectMake(0, 0, 100, 40) 

    self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button) 
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "+", style: .Plain, target: self, action: nil) 
    self.navigationItem.rightBarButtonItem?.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFontOfSize(40)], forState: .Normal) 

} 
+0

,謝謝。我試圖將按鈕添加到導航控制器,而不是它包含的視圖控制器。 –

+0

很高興聽到這個消息。將其標記爲答案plz – ha100

1

的UINavigationController的是沒有XIB文件自身的.swift文件。

在UIViewController類中創建此按鈕,而不是在您的UINavigationController中。所以將相同的代碼移到你的UIViewController。

+0

這並不工作,標題顯示不出來這個工作這種方式要麼 –

相關問題