ios - 添加 xib tableview 单元格的 subview (swift)

标签 ios swift uitableview

我创建了一个tableview和xib tableviewcell 。我使用xib tableviewcell通过添加 subview 。但似乎失去了 func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) 的功能

我想要这个定制tableviewcell继承正常cell在我的tableview 。 如何做到这一点??

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

override func viewDidLoad() {
    super.viewDidLoad()

    var myTableView = UITableView(frame: self.view.bounds, style: UITableViewStyle.Plain)
    myTableView.dataSource = self
    myTableView.delegate = self

    myTableView.backgroundColor = UIColor.whiteColor()

    myTableView.frame = CGRectMake(20, 50, 250, 400)//Optional for table size

    myTableView.registerNib(UINib(nibName: "MyTableViewCell", bundle: nil), forCellReuseIdentifier: "myIdentifier")

    self.view.addSubview(myTableView)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

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

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

    let myCell = tableView.dequeueReusableCellWithIdentifier("myIdentifier") as! MyTableViewCell
    myCell.myString1.text = "Row \(indexPath.row)"
    myCell.myString2.text = "String \(indexPath.row)"
    return myCell
}

}

最佳答案

您需要继承 UITableViewController,而不是 UIViewController。因此:

class ViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate {
    super.viewDidLoad()

    self.tableView.dataSource = self
    self.tableview.delegate = self
    self.tableview.backgroundColor = UIColor.whiteColor()
    self.tableView.registerNib(UINib(nibName: "MyTableViewCell", bundle: nil), forCellReuseIdentifier: "myIdentifier")
)

关于ios - 添加 xib tableview 单元格的 subview (swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37648802/

相关文章:

ios - 每次运行 cellforrow 方法时都必须刷​​新 Firebase 数据吗?

ios - 按比例填充 UIStackView?

ios - 主要细节中的 child 计数器

Swift 3.0 排序 - 传递给不带参数的调用的参数

string - 如何在有引号的字符串周围加上引号?

ios - UITableView 单元格的阴影在表格滚动后改变位置

ios - 为 Firebase 6.5.0 安装 Geofirestore

ios - 如何将 sqlite 数据库转换为 ios 中的核心数据

ios - 如何使 UISearchController 中的范围栏在 Ios swift 中始终可见?

ios - UISearchController 保留问题