简体   繁体   English

添加Xib TableView单元的子视图(Swift)

[英]Add subview of xib tableview cell (swift)

I have created a tableview and xib tableviewcell . 我创建了一个tableview和xib tableviewcell i use the xib tableviewcell by adding subview. 我通过添加子视图来使用xib tableviewcell however it seems lost the function of func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) 但是它似乎失去了func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)

i want this custom tableviewcell inherit the normal cell in my tableview . 我希望这个自定义tableviewcell继承我tableview的普通cell 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. 您将要继承自UITableViewController,而不是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")
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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