setRightBarButtonItems 不起作用

setRightBarButtonItems doesn't work

我想在 UINavigationBar 的右侧设置 2 个按钮。下面是源代码。没有错误,但也没有按钮。它是 UIViewController,而不是 UINavigationViewController

let buttonEdit: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
buttonEdit.frame = CGRectMake(0, 0, 40, 40)
buttonEdit.setImage(UIImage(named:"me44.png"), forState: UIControlState.Normal)
buttonEdit.addTarget(self, action: "rightNavItemEditClick:", forControlEvents: UIControlEvents.TouchUpInside)
var rightBarButtonItemEdit: UIBarButtonItem = UIBarButtonItem(customView: buttonEdit)

let buttonDelete: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
buttonDelete.frame = CGRectMake(0, 0, 40, 40)
buttonDelete.setImage(UIImage(named:"me44.png"), forState: UIControlState.Normal)
buttonDelete.addTarget(self, action: "rightNavItemDeleteClick:", forControlEvents: UIControlEvents.TouchUpInside)

var rightBarButtonItemDelete: UIBarButtonItem = UIBarButtonItem(customView: buttonDelete)

// add multiple right bar button items       
self.navigationController?.navigationItem.setRightBarButtonItems([rightBarButtonItemDelete, rightBarButtonItemEdit] as [AnyObject], animated: true)

//I also tried code below no luck either
self.navigationItem.setRightBarButtonItems([rightBarButtonItemDelete, rightBarButtonItemEdit] as [AnyObject], animated: true)

这段代码是错误的:

self.navigationController?.navigationItem.setRightBarButtonItems(
    [rightBarButtonItemDelete, rightBarButtonItemEdit] as [AnyObject], animated: true)

您没有设置导航控制器的navigationItem;你设置 你的 navigationItem。另外, [AnyObject] 是不必要的。所以:

self.navigationItem.setRightBarButtonItems(
    [rightBarButtonItemDelete, rightBarButtonItemEdit], animated: true)

但是,请注意,只有当您的视图控制器是 UINavigationController 的子级时,它才有效。设置视图控制器的 navigationItem 只会在这种情况下自动填充导航栏。如果您 不是 在那种情况下 — 即,如果您的界面中只有一个 "loose" 导航栏 — 您需要 手动填充导航栏(通过设置its navigationItem)。

(另外,请注意,如果您没有 "me44.png" 图片,可能是您的代码正在运行,但您只是 看不到 任何东西。)

尽管前面已经指出,您可能看不到添加到导航栏的按钮。对于Swift 3,在AppDelegate class中试试这个(注意topItem):

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    window = UIWindow()
    window?.backgroundColor = UIColor.white

    let navigationVC = UINavigationController(rootViewController: UIViewController())

    let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addTodo))
    navigationVC.navigationBar.topItem?.rightBarButtonItem = addButton

    window?.rootViewController = navigationVC
    window?.makeKeyAndVisible()

    return true
}