将自定义 UIBarButtonItem 添加到 UINavigationBar

Adding a custom UIBarButtonItem to a UINavigationBar

我正在尝试将一个大的加号按钮作为右栏按钮,下面的代码在故事板中时有效,但是在将所有内容移动到 xib 文件并分离 .swift 文件之后,这是唯一坏掉的东西。

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 文件。

我不明白为什么它在情节提要中起作用,但现在不起作用。

理想情况下,我想要一个大的加号按钮(因为正常的字体大小似乎有点小)

The UINavigationController is its own .swift file with no xib file.

在 UIViewController class 而不是 UINavigationController 中创建此按钮。所以将相同的代码移动到您的 UIViewController。

对我有用。我刚刚摆脱了目标行动,所以我不必实施它。全部用代码完成。没有故事板,也没有 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)

}