使用 swift 访问 UIBarButtonItem textfield.text

Accessing UIBarButtonItem textfield.text using swift

我在视图底部的工具栏中有一个文本字段,可用于发表评论。

@IBOutlet var commentText: UIBarButtonItem!

@IBAction func commentButton(sender: AnyObject) {

    println(commentText.text) // dosent work
}

我正在尝试获取 textfield.text 但我不能只说 commentText.text 因为它是一个 UIBarButtonItem。我试过 commentText.target!.text 但没有用。我 2 周前才开始使用 swift,所以我使用故事板来放入项目,而不是以编程方式制作它们

UITextField 是 UIBarButtonItem 的 customView。但即便如此,customView 也只是一个 UIView,因此您必须将其转换为告诉编译器它是一个 UITextField。

所以:

println((commentText.customView as! UITextField).text)