我一直在尝试创建通过xib加载的自定义视图,该视图包含一个按钮和tableview。当按下按钮时,表格视图显示或隐藏。
此交互有效,并且表已创建/显示。我的问题是我无法单击表行。
我一直在寻找并没有找到有效的解决方案。
我确保已设置委托和数据源。我也没有用于ViewController的GestureRecognizer,因为它可以吸收触摸。
有人知道我在想什么吗?
这是此自定义视图的代码:
class SubUnitSpinner : UIView, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var spinnerTableView: UITableView!
let subUnitNames: [String] = ["World", "Add/Remove"]
override init( frame: CGRect ) {
super.init(frame: frame)
loadViewFromNib()
setupTableView()
}
required init?( coder aDecoder: NSCoder ) {
super.init(coder: aDecoder)
loadViewFromNib()
setupTableView()
}
func setupTableView() {
spinnerTableView.delegate = self
spinnerTableView.dataSource = self
spinnerTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
spinnerTableView.rowHeight = 30
spinnerTableView.userInteractionEnabled = true
spinnerTableView.allowsSelection = true
spinnerTableView.hidden = true
}
func loadViewFromNib() {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: "SubUnitSpinner", bundle: bundle)
let xibView = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
xibView.frame = bounds
xibView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
self.addSubview(xibView)
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = spinnerTableView.dequeueReusableCellWithIdentifier("Cell")! as UITableViewCell;
cell.userInteractionEnabled = true
cell.textLabel?.text = subUnitNames[indexPath.row]
cell.tag = indexPath.row
return cell;
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//Interaction
print("cell with path: \(indexPath.row)")
}
@IBAction func spinnerTabbed(sender: AnyObject) {
spinnerTableView.hidden = !spinnerTableView.hidden
} }
更新:
视图布局创建:
xib视图布局已在“故事板”中定义,并且“文件的所有者”设置为SubUnitSpinner。通过ctrl拖放创建的IBOutlet和IBAction。
在UIViewController中的用法:
我将其用作故事板中也已定义的UIViewController的一部分。我添加了一个UIView并将自定义类声明为SubUnitSpinner。
运行xib时,将显示具有xib中定义的布局的SubUnitSpinner,并且该按钮是可单击的,当显示按钮时,将显示/隐藏UITableView。唯一不起作用的是单击tableView单元格。
设置有问题吗?
最佳答案
我只是拿了您的代码,并将其添加到一个虚拟项目中进行检查。我这样做是为了你的方法
required init?( coder aDecoder: NSCoder ) {
super.init(coder: aDecoder)
// removed the load from nib and setup tableview
}
就我而言,我执行了以下操作以将
SubUnitSpinner
视图添加到父视图。希望你也一样let aTestView = SubUnitSpinner(frame: CGRectMake(50, 200, 200, 200))
view.addSubview(aTestView)
还要仔细检查您是否已连接来自xib的任何委托和数据源。总而言之,您的代码看起来不错,我能够正确单击它。以下是我取得的成绩。
关于ios - 在xib中定义的SubView中定义的TableView中未调用didSelectRowAtIndexPath,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38298489/