【问题标题】:Swift Compiler error while referencing existing variable [duplicate]引用现有变量时出现 Swift 编译器错误 [重复]
【发布时间】:2015-03-28 23:26:00
【问题描述】:

我正在尝试为 UITextView 手动创建一些占位符文本,当我尝试设置占位符文本时,我收到 Swift 编译器错误。 Xcode 告诉我它需要一个 pinContent 声明,我首先尝试设置它的文本值。这是我的代码:

class FirstViewController: UIViewController {

@IBOutlet var pinTitle: UITextField!

@IBOutlet var pinContent: UITextView!

@IBAction func createPin(sender: AnyObject) {



}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    println(userLocation)
}

// Manually create a placeholder for the text view
pinContent.text = "Description" // This line is where I get my error
pinContent.textColor = UIColor.lightGrayColor()

// Change the text properties of the text view when the user begins editing, so it types in the normal black font
func textViewDidBeginEditing(textView: UITextView) {
    if textView.textColor == UIColor.lightGrayColor() {
        textView.text = nil
        textView.textColor = UIColor.blackColor()
    }
}

// If the user leaves the text view blank when they're done editing, re-set the placeholder
func textViewDidEndEditing(textView: UITextView) {
    if textView.text.isEmpty {
        textView.text = "Description" // Sometimes I get the same error here as well
        textView.textColor = UIColor.lightGrayColor()
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

【问题讨论】:

  • 将该代码移入方法中(例如移入 viewDidLoad)...

标签: swift compiler-errors uitextview declaration


【解决方案1】:

问题似乎是您想将文本设置在方法或闭包的范围之外。
试试这个:

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view, typically from a nib.
    // Manually create a placeholder for the text view

    pinContent.text = "Description" // This line is where I get my error
    pinContent.textColor = UIColor.lightGrayColor()
    println(userLocation)
}

【讨论】:

  • 嗨赫比和马丁,感谢您的快速回复。我将代码移到 viewDidLoad() 中,现在当我运行应用程序时,它立即崩溃。以下是我在控制台中得到的信息: *** 由于未捕获的异常“NSUnknownKeyException”而终止应用程序,原因:“[ setValue:forUndefinedKey:]:此类与键 createPin 的键值编码不兼容。对此有什么想法吗?
  • 看起来您的故事板中有一个陈旧的 iboutlet 定义。检查它们是否都正确连接
  • 你是对的,我的 main.storyboard 中的连接不正确,而我的主视图控制器中不存在该连接。我进去并删除了所有连接并重新添加它们并且它起作用了。
猜你喜欢
  • 2014-08-16
  • 2014-08-05
  • 2016-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-30
相关资源
最近更新 更多