如何检测是否点击了表格视图单元格。 Web上的指南和教程遵循向表格单元格视图添加按钮的方法 - 原型单元格。此按钮对于所有行保持相同,并且在点击时,返回行或单元格的索引。
我想在没有按钮的情况下这样做。我该如何调用
@IBAction
当点击一个单元格然后在函数内执行一个segue时。
我应该怎么做?
我添加了以下代码,但这不会打印任何内容
class MoreViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let moreOption = [
("My Profile"),
("Settings"),
("Logout")
]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.navigationController!.navigationBar.barTintColor = UIColor(red: (48/255.0), green: (187/255.0), blue: (197/255.0), alpha: 1.0);
self.navigationController!.navigationBar.tintColor = UIColor .whiteColor();
self.navigationController!.navigationBar.translucent = false;
self.navigationController!.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor .whiteColor()]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func logout() {
print("Logout tapped");
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return moreOption.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
let (celloption) = moreOption[indexPath.row];
cell.textLabel!.text = celloption;
cell.textLabel!.textColor = UIColor(red: (74/255.0), green: (74/255.0), blue: (74/255.0), alpha: 1.0);
return cell;
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.cellForRowAtIndexPath(indexPath)
print(cell);
}
}
答案 0 :(得分:2)
为什么不使用UITableViewDelegate方法?
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
在这种方法中,您将获得单元格的indexPath,如果需要,您可以在此处打开新控制器。
答案 1 :(得分:0)
试一下
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectedItem = items.objectAtIndex(indexPath.row) as String
print(selectedItem)
}
答案 2 :(得分:0)
在代码中,您没有添加tableview出口(如果从代码构建它,则为变量)。 您需要先将tableview出口添加到您的类中,然后为其设置适当的委托和数据源
例如
//this is connected to your storyboard
//It may have typing errors it is not tested
//at this on the top of your class
@IBOutlet weak var table: UITableView!
//at this on viewdidLoad or viewDidAppear
table.delegate = self
table.datasource = self