didSelectRowAtIndexPath未被调用(Swift)

Jav*_*les 10 uitableview ios swift

我已经在圈子里呆了一段时间,我在相关帖子中发现的任何内容似乎都无法解决.我是以编程方式将表添加到自定义UIView中.表格和行文本显示正确,但是当我在模拟器上运行并尝试单击任何行时,didSelectRowAtIndexPath和willdSelectRowAtIndexPath都不会触发.

我的代码的相关位如下:

import UIKit
import AVFoundation

@IBDesignable
class PerformanceQuestionView: UIView, UITableViewDelegate, UITableViewDataSource {

var optionsTable = UITableView(frame: CGRectMake(10,200,250,200))

var optionItems = ["One", "Two", "Three", "Four"]

convenience init(rect: CGRect, performanceQuestion:PerformanceQuestion?) {
    self.init(frame: rect)

    NSLog("PerformanceQuestionView.init()")

    self.optionsTable.dataSource = self
    self.optionsTable.delegate   = self
    self.optionsTable.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
    self.optionsTable.allowsSelection   = true
}

func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
    NSLog("numberOfRowsInSection")
    return optionItems.count
}

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
    NSLog("cellForRowAtIndexPath")
    var cell:UITableViewCell = self.optionsTable.dequeueReusableCellWithIdentifier("cell") as UITableViewCell

    cell.textLabel.text = self.optionItems[indexPath.row]

    return cell
}

func tableView(tableView: UITableView!, willSelectRowAtIndexPath indexPath: NSIndexPath!) -> NSIndexPath! {
    NSLog("You will select cell #\(indexPath.row)!")
    return indexPath
}

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    NSLog("You selected cell #\(indexPath.row)!")
}

override func layoutSubviews() {

    super.layoutSubviews()

    self.addSubview(optionsTable)
}

}
Run Code Online (Sandbox Code Playgroud)

AAA*_*AAA 25

删除TapGestureRecognizer对我有用!!!

    // var backgoroundTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "DismissKeyboard")
    // self.view.addGestureRecognizer(backgoroundTap)
Run Code Online (Sandbox Code Playgroud)

  • 创建一个单独的视图并在该视图内加载标签和按钮。然后单独添加该视图的手势。它会工作。 (2认同)

Gih*_*han 14

原因可能是,您在视图中使用平移手势.像AAA提到删除你的平移手势将成功.但如果您仍想使用平移手势,则可以执行以下操作

    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
    view.addGestureRecognizer(tap)
    tap.cancelsTouchesInView = false
Run Code Online (Sandbox Code Playgroud)

制作cancelsTouchesInView,false将启用你所有的点击.


Aar*_*ger 3

去掉感叹号:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

}
Run Code Online (Sandbox Code Playgroud)

  • @JavierArtiles 视图层次结构中的某些内容可能会阻止触摸。“PerformanceQuestionView”的框架至少与表格的框架一样大吗? (3认同)