gpt4 book ai didi

ios - 从 XIB 调用函数时 tableView 为 nil

转载 作者:行者123 更新时间:2023-11-29 02:31:28 30 4
gpt4 key购买 nike

我有一个工作正常的 tableView。内容已正确填充。我在导航栏中也有几个按钮来过滤 tableView 和 reloadData 的内容。一切都很好。

但现在我正在尝试拥有一个自定义的 tableview header ,以便在其中放置一些按钮。我创建了一个 XIB 文件并将其添加到 TableView 标题中。

MainViewController.swft

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {       
var headerxib:UIView = NSBundle.mainBundle().loadNibNamed("headerView", owner: self, options: nil).first as UIView
var tableheader = UIView(frame: CGRectMake(0, 0, 300, 80))
tableHeader.addSubview(headerxib)
return tableHeader
}

// This is the function that I'm trying to run
func justReload(){
println("reload \(tableView)")
tableView.reloadData()
}

到目前为止一切都很好。然后我在我的 XIB swift 文件中创建了 IBAction 以从主视图 Controller (带有 tableview 的那个)调用一个函数

headerView.xib

@IBAction func touhcbb(sender: AnyObject) {
let vc = MainViewController()
vc.justReload()
}

所以,问题来了。 justReload() 函数中的 println() 显示 tableView 为 nil。导致 reloadData() 出错。

如果从外部 XIB 文件调用该函数,为什么它是 nil?

当我尝试从同一个 ViewController 中的 IBOutlet 调用该函数时,一切正常。

如果有人有任何提示或线索可以指出我正确的方向,我将不胜感激。谢谢!

最佳答案

打开您的 xib,并将文件所有者的类设置为 MainViewController: enter image description here

MainViewContrtoller.swift

class MainViewController: UITableViewController {
// Use IB to connect the button to this action method.
@IBAction func touhcbb(sender: AnyObject) {
justReload()
}

func justReload(){
println("reload \(tableView)")
tableView.reloadData()
}

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
var headerxib:UIView = NSBundle.mainBundle().loadNibNamed("headerView", owner: self, options: nil).first as UIView

var tableheader = UIView(frame: CGRectMake(0, 0, 300, 80))
tableHeader.addSubview(headerxib)

return tableHeader
}
}

关于ios - 从 XIB 调用函数时 tableView 为 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26817764/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com