ios - 如何从 subview 访问父 View 的 View Controller

标签 ios swift iphone xcode

我正在创建一个 UIView,其中将包含一个 UITableView。我想将此 UITableView 委托(delegate)和数据源设置为其父 View 的 View Controller 。

代码:

import UIKit

class AllTasksView: UIView {

    let tableview = UITableView()

    override init(frame: CGRect) {
        super.init(frame: frame)

    }


    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

    }
     override func didMoveToSuperview() {
    tableview.delegate = "SUPERVIEW.ViewController"
    tableview.dataSource = "SUPERVIEW.ViewController"
}

这样可以吗?在哪里最好覆盖 UITableview 方法?我已经在我的 UIViewController 中这样做了。

最佳答案

由于关注点分离,您无法从 UIView 访问 UIViewController

或者,您可以使用委托(delegate)来访问 UIViewController

   class AllTasksView{
       weak var delegate: UITableViewDataSource & UITableviewDelegate?{
           didSet{
               tableView.delegate = newValue
               tableView.dataSource = newValue
           }
       }


   }

额外的

       class CustomVC: UIViewController, UITableViewDelegate, UITableViewDataSource{
          //implement tableview methods here 


           func viewDidLoad(){
               super.viewDidLoad()

              let allTasksView = AllTasksView()
              view(addSubview: allTasksView)

              //add some positioning and size constraints here for allTasksView 

              allTasksView.delegate = self //this would call the didSet and would automatically setup the allTasksView.tableView's delegate and dataSource to this vc
           }
       }

关于ios - 如何从 subview 访问父 View 的 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55863963/

相关文章:

ios - Swift 4/Firebase - 从不同数组中的实时数据库读取和存储双重嵌套项目

ios - Xcode 7 : WatchOS storyboards do not support target device type 'iphone'

iphone - 在 Objective-C 中获取 id 的字符串表示

ios - iOS 上的多个用户

javascript - 高效检测设备是否会播放具有自动播放属性的无声视频

ios - Entitlements.entitlements 有什么作用?

ios - iOS 的推荐数据大小是多少

Swift:我如何等到变量具有特定值

ios - 使用位置管理器时,我的 Swift 应用程序耗电非常快

ios - 延迟 CABasicAnimation 会立即绘制它