【问题标题】:Swift - UIView.text Showing Up as NilSwift - UIView.text 显示为 Nil
【发布时间】:2016-06-24 20:02:11
【问题描述】:

我是 Swift 初学者。我正在创建一个简单的 Parse 记事本 iOS 应用程序,以供练习。我正在尝试从一个类访问在另一个类中创建的 uitextview。这会导致 uitextview 为 nil 的错误。

例如,我的 tableviewcell 类很简单,只有两个 uiview 连接到它(插座连接正确):

 @IBOutlet weak var titleLabel: UITextView!

@IBOutlet weak var descriptionLabel: UITextView!

 override func awakeFromNib() {
        titleLabel.text = "Title"
        descriptionLabel.text = "Description"
    }

然后我尝试从我的 detailviewcontroller 类中访问这些属性,但出现错误 “unexpectedly found nil when unwrapping an optional”,即使我的 titleLabel 和 descriptionLabel 都具有以编程方式设置的值.

detailviewcontroller 类(在 viewdidload 中):

let customCell = TableViewCell()

    var Title = customCell.titleLabel.text
    let Description = customCell.descriptionLabel.text

非常感谢您的帮助。谢谢。

*另外请注意我的 IBOutlets 连接正确

【问题讨论】:

  • 这有什么更新吗?我也面临同样的问题!

标签: ios swift uiview optional


【解决方案1】:

只有这一行的问题

let customCell = TableViewCell()

可以通过多种方式将值传递给 DetailViewController,如果您通过 segue 更改视图,则可以使用此

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
    //add if condition with segue identifier for proper functioning of this code

    let selectedIndexPath = tableView.indexPathForSelectedRow!
    let customCell = tableView.cellForRowAtIndexPath( selectedIndexPath ) as! TableViewCell

    let destinationViewController = segue.destinationViewController as! DetailViewController
    destinationViewController.Title = customCell.titleLabel.text!
    destinationViewController.Description = customCell.descriptionLabel.text!
    //you can set other properties too here
}

在您的 DetailViewController 中,在函数 viewdidload 之外声明变量 Title 和 Description

【讨论】:

  • 不要将willSelectRow...中的新单元格出列,使用tableView.cellForRowAtIndexPath(indexPath)获取当前单元格
  • 为什么 dequeueReusableCellWithIdentifier 在 willSelectRowAtIndexPath 中?
  • @pratikxman 但我希望能够在 detailviewcontroller 中访问单元格,而不是 masterviewcontroller。这可能吗?谢谢。
  • @pratikxman 非常感谢您的回答。我只有一个问题,那就是由于某种原因没有调用 prepareForSegue 函数(我把它放在 detailviewcontroller 中)。你知道为什么会这样吗?谢谢。
  • @StephaneHatgiskessell 上面的代码函数 prepareForSegue 应该在您的 tableviewcontroller 中,并且只有在 segue 完成转换时才会起作用。你能解释一下你是如何从 tableviewcontroller 到 detailviewcontroller 再回到 tableviewcontroller
猜你喜欢
  • 2019-05-07
  • 1970-01-01
  • 2016-09-05
  • 2014-08-30
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 2020-09-04
  • 1970-01-01
相关资源
最近更新 更多