我有一个带有容器视图的视图控制器,其中包含一个静态UITableViewController
作为菜单。父视图控制器是UIPageViewController
的一部分。
每当用户单击一行时,我都想调用一个函数以从PageViewController执行segue。为此,我在didSelectRowAt
中添加了MenuTableViewController
。 -由于正在执行打印请求,因此此功能工作正常。
为了从PageViewController调用函数,我尝试使用委托,但不知何故该函数无法执行。
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
let vc = storyboard?.instantiateViewController(withIdentifier: "menuView") as! MenuTableViewController
vc.delegate = self
...
}
func goToMap() {
performSegue(withIdentifier: "goMap", sender: self)
}
class MenuTableViewController: UITableViewController {
let defaults = UserDefaults.standard
weak var delegate: RootPageViewController?
}
extension MenuTableViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(indexPath.row)
if indexPath.row == 2 {
delegate?.goToMap()
}
tableView.deselectRow(at: indexPath, animated: true)
}
}
编辑:在PageViewController的viewDidLoad()中
let home = storyboard?.instantiateViewController(withIdentifier: "homeView") as! HomeViewController
home.loadViewIfNeeded()
let menu = home.children[1] as! MenuTableViewController
print("Children:", home.children)
menu.delegate = self
class RootPageViewController: UIPageViewController, UIPageViewControllerDataSource, UIScrollViewDelegate, UIViewControllerTransitioningDelegate {
lazy var viewControllerList:[UIViewController] = {
let sb = UIStoryboard(name: "Main", bundle: nil)
let vc1 = sb.instantiateViewController(withIdentifier: "homeView")
let vc2 = sb.instantiateViewController(withIdentifier: "timelineView")
return [vc1, vc2]
}()
let defaults = UserDefaults.standard
let transition = CircularTransition()
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
let home = storyboard?.instantiateViewController(withIdentifier: "homeView") as! HomeViewController
home.delegate = self
print(home.delegate)
if let secondViewController = viewControllerList.first as? HomeViewController {
self.setViewControllers([secondViewController], direction: .forward, animated: true, completion: nil)
....
最佳答案
您为menuVc创建另一个对象并为其分配委托,它不同于情节提要中的1,因此PagerVC的内部viewDidLoad
let home = //
let menu = home.children.first as! MenuTableViewController
menu.delegate = self
关于ios - 委托(delegate)将不执行功能,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56307304/