【问题标题】:Instance member 'navigationItem' cannot be used on type 'MainViewController'实例成员“navigationItem”不能用于“MainViewController”类型
【发布时间】:2017-01-25 22:19:25
【问题描述】:

使用 xcode8 似乎无法摆脱这种恐惧:

编译失败并显示消息:Instance member 'navigationItem' cannot be used on type 'MainViewController'

class MainViewController: UITableViewController {

    private static var __once: () = {
                let loginButton: UIBarButtonItem = UIBarButtonItem(title: nil, style: .done, target: self, action: nil)
                MainViewController.navigationItem.rightBarButtonItem = loginButton
        }()

这是调用它的函数:

func setupRightBarButtonItem() {
            struct Static {
                static var onceToken: Int = 0
            }

            _ = MainViewController.__once

            if (AWSIdentityManager.default().isLoggedIn) {
                navigationItem.rightBarButtonItem!.title =     NSLocalizedString("Sign-Out", comment: "Label for the logout button.")
                navigationItem.rightBarButtonItem!.action =     #selector(MainViewController.handleLogout)
            }
    }

【问题讨论】:

  • 你想做什么?这是行不通的,因为正如消息所说,你不能在类类型上使用实例属性
  • 我正在尝试设置 AWA SES 并获取从他们的模板 aws-my-sample-app-ios-swift v0.3 生成的一些源代码工作。
  • 好吧,写模板的人不应该被允许靠近 Swift,如果那是他们发布的内容。

标签: ios iphone swift xcode8


【解决方案1】:

看起来您正在尝试在第一次调用 setupRightBarButtonItem 时创建右栏按钮项,但我不确定您是从哪里得出此代码的。

消息很清楚,navigationItem 是一个实例属性,您正在尝试将其用作类属性。

为什么不使用更直接的方法:

func setupRightBarButtonItem() {

    if navigationItem.rightBarButtonItem == nil {       
        navigationItem.rightBarButtonItem = 
            UIBarButtonItem(title: nil, style: .done, target: self, action: nil)    
    }

    if (AWSIdentityManager.default().isLoggedIn) {
            navigationItem.rightBarButtonItem!.title =     NSLocalizedString("Sign-Out", comment: "Label for the logout button.")
            navigationItem.rightBarButtonItem!.action =     #selector(MainViewController.handleLogout)
    } 
    // You probably need an `else` clause here to update the button if the user isn't logged in?
}

【讨论】:

    猜你喜欢
    • 2015-11-27
    • 2016-05-23
    • 2016-01-01
    • 2016-09-09
    • 2020-01-16
    • 2017-06-25
    • 2016-07-05
    • 2019-02-15
    相关资源
    最近更新 更多