简体   繁体   中英

Add subview of xib tableview cell (swift)

I have created a tableview and xib tableviewcell . i use the xib tableviewcell by adding subview. however it seems lost the function of func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)

i want this custom tableviewcell inherit the normal cell in my tableview . how to do that??

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
}

}

You'll want to inherit from UITableViewController, and not UIViewController. As such:

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")
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM