【发布时间】:2015-10-26 21:23:15
【问题描述】:
我在 Swift 方面不是很有经验。我有一个 tableView 和自定义单元格,其中有几个标签 UISlider 和 UISwitch。
当我更改滑块值并点击提交(条形按钮项)时,我想从所有单元格中收集 UISlider 和 UISwitch 值。
我尝试了什么:
1.Tags:我到达了一些单元格,但是停下来无法到达当前不可见的单元格,最后阅读了一些意见,标签不太可能使用。
问题:有没有明确的赞成和反对?
2.CellForRowAtIndexPath:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CustomTableViewCell") as! CustomTableViewCell
cell.Label1.text = "Long Tongue, size \(indexPath.row) cm"
cell.Label2.text = "Big Banana, size \(indexPath.row) inches"
return cell
}
@IBAction func submitTapped(sender: AnyObject) {
let cell = tableView(self.tableView , cellForRowAtIndexPath: NSIndexPath(forRow: 1, inSection: 0)) as! CustomTableViewCell
print(cell.Label1.text) // gives me
print(cell.Label2.text) // values
print(cell.customSlider.value) // gives me the value stated as
print(cell.customSwitch.on) // default
}
我理解正确吗,我在这里调用 cellForRowAtIndexPath ,难怪我得到了自定义单元的新实例(由函数处理)?
3.“摇狗”
不幸的是,我失去了讨论此解决方案的 SO 链接:(
我尝试使用 .superview.superview 访问 UIViewController ...,但 Xcode 拒绝吃 4 个超级视图(我不确定我是否找到了正确数量的 .superviews)。
主要思想是在自定义单元格中提供对 UIViewController 属性的访问权限:
在 CustomTableViewCell 中添加一个属性:
class CustomTableViewCell: UITableViewCell {
var viewController : MyViewController?
var cellNo = 0
//and so on
}
class MyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var sliderValues: [Float] = []
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CustomTableViewCell") as! CustomTableViewCell
cell.Label1.text = "Long Tongue, size \(indexPath.row) cm"
cell.Label2.text = "Big Banana, size \(indexPath.row) inches"
self.sliderValues.append (0.0) // just to be sure that each slider can put it's value to Array
cell.cellNo = indexPath.row // so the Custom Cell knows it's No
//---------------------//
cell.viewController = self
//---------------------//
return cell
}
}
//----------------------
//and back to Custom Cell
@IBAction func sliderValueChanged(sender: AnyObject) {
self.viewController?.sliderValues[self.cellNo] = self.customSlider.value
}
// and the same way with UISwitch
好消息,这行得通!
问题:有什么方法可以不“摇狗”并从 UIViewController 到达 Custom Cell?
【问题讨论】:
-
模型 - 视图 - 控制器。模型-视图-控制器。不要不使用单元格(视图)来保持状态。当用户进行更改时,更改 model。从 model 获取控制器中的更改。
-
是的,这就是为什么我称它为“摇狗”,并且完全不满意!
标签: ios swift uitableview uiviewcontroller tableviewcell