ios 遵守 ViewController 中的协议,在 Swift 中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24092346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:37:17  来源:igfitidea点击:

Conform to protocol in ViewController, in Swift

iosprotocolsswift

提问by Justin

Trying to conform to UITableViewDataSource and UITableViewDelegate inside a Swift UIViewController subclass.

试图在 Swift UIViewController 子类中符合 UITableViewDataSource 和 UITableViewDelegate。

class GameList: UIViewController {

    var aTableView:UITableView = UITableView()

    override func viewDidLoad() {
        super.viewDidLoad()
        aTableView.delegate = self
        aTableView.dataSource = self
        self.view.addSubview(aTableView)
        //errors on both lines for not conforming
    }

}

Docs say you should conform on the classline after the :but that's usually where the superclass goes. Another :doesn't work. Using a comma separated list after the superclass also doesn't work

文档说你应该在class后面的行上符合,:但这通常是超类去的地方。另一个:不起作用。在超类之后使用逗号分隔的列表也不起作用

EDIT:

编辑:

Also must adopt all required methods of each protocol, which I wasn't initially doing.

还必须采用每个协议的所有必需方法,我最初没有这样做。

回答by Firo

You use a comma:

您使用逗号:

class GameList: UIViewController, UITableViewDelegate, UITableViewDataSource {
    // ...
}

But realize that the super class must be the first item in the comma separated list.

但是要意识到超类必须是逗号分隔列表中的第一项。

If you do not adopt all of the required methods of the protocol there will be a compiler error. You must get all of the required methods!

如果您没有采用协议的所有必需方法,则会出现编译器错误。您必须获得所有必需的方法!

回答by Berby Huang

As XCode6-Beta7 releases,

随着 XCode6-Beta7 的发布,

I noticed the protocol method of UITableViewDataSource changed a little bit and sounded the same conform to protocol error which worked fine in beta6.

我注意到 UITableViewDataSource 的协议方法发生了一些变化,听起来与在 beta6 中运行良好的协议错误相同。

These are the required methods to be implemented according to the UITableViewDataSource protocol:

这些是根据UITableViewDataSource 协议实现的必需方法:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // insert code}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // insert code
}

You might want to re-check the difference or re-implement the delegate method that you thought you just implement.

您可能想要重新检查差异或重新实现您认为刚刚实现的委托方法。

回答by Kiet Nguyen

You must implement two require methods here:

您必须在此处实现两个 require 方法:

func tableView(tableView:UITableView!, numberOfRowsInSection section:Int) -> Int {
    return 10
}

func tableView(tableView:UITableView!, cellForRowAtIndexPath indexPath:NSIndexPath!) -> UITableViewCell! {
    let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "MyTestCell")

    cell.text = "Row #\(indexPath.row)"
    cell.detailTextLabel.text = "Subtitle #\(indexPath.row)"

    return cell
}

回答by skipy

Also, it is important to copy all the non optional functions from the Delegate class. Cmd + Click on the UITableViewDatasource and copy those two definitions as is.

此外,从 Delegate 类复制所有非可选函数也很重要。Cmd + 单击 UITableViewDatasource 并按原样复制这两个定义。

For me in beta7, the UITableViewDatasource has

对于 beta7 中的我来说,UITableViewDatasource 有

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell

My implementation:

我的实现:

var items = ["Apple", "Pear", "Banana"]

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return items.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell:UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Default")
    cell.textLabel?.text = items[indexPath.row]
    cell.detailTextLabel?.text = "Test"
    return cell

}

回答by Rohit Ragmahale

Usee These methods: There is change in Data source methods-

使用这些方法:数据源方法有变化-

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell


protocol UITableViewDataSource : NSObjectProtocol {

    ****func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int

    // Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
    // Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell****

    optional func numberOfSectionsInTableView(tableView: UITableView) -> Int // Default is 1 if not implemented

    optional func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? // fixed font style. use custom view (UILabel) if you want something different
    optional func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String?

    // Editing

    // Individual rows can opt out of having the -editing property set for them. If not implemented, all rows are assumed to be editable.
    optional func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool

    // Moving/reordering

    // Allows the reorder accessory view to optionally be shown for a particular row. By default, the reorder control will be shown only if the datasource implements -tableView:moveRowAtIndexPath:toIndexPath:
    optional func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool

    // Index

    optional func sectionIndexTitlesForTableView(tableView: UITableView) -> [AnyObject]! // return list of section titles to display in section index view (e.g. "ABCD...Z#")
    optional func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int // tell table which section corresponds to section title/index (e.g. "B",1))

    // Data manipulation - insert and delete support

    // After a row has the minus or plus button invoked (based on the UITableViewCellEditingStyle for the cell), the dataSource must commit the change
    // Not called for edit actions using UITableViewRowAction - the action's handler will be invoked instead
    optional func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)

    // Data manipulation - reorder / moving support

    optional func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath)
}

Ur code will works!!

你的代码会起作用!!

回答by Sahil Manchanda

This question is already answered but just want to make things a bit more Swifty.

这个问题已经得到了回答,但只是想让事情变得更加 Swifty。

Instead of writing protocols in UITableViewDelegate, UITableViewDataSourceyou can divide them using extensionsthis will help in organising the code. Adding protocol conformance is described in this page

UITableViewDelegate, UITableViewDataSource您可以使用扩展划分它们,而不是在其中编写协议, 这将有助于组织代码。此页面中描述了添加协议一致性

for the above question, this can be confirmed to protocol using extension:

对于上述问题,可以使用扩展名向协议确认:

class GameList: UIViewController {
  var aTableView:UITableView = UITableView()
    override func viewDidLoad() {
        super.viewDidLoad()
        aTableView.delegate = self
        aTableView.dataSource = self
        self.view.addSubview(aTableView)
    }
}
extension GameList: UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return list.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath)
        return cell
    }
}
extension GameList: UITableViewDelegate{
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("Row Clicked at \(indexPath.row)")
    }
}