在我的主页中,我为UITableViewCell创建了一个xib文件。我正在从xib文件加载单元格,它工作正常。
在细胞里面我有一些标签和按钮。我的目标是通过单击单元格上的按钮来更改标签。
我的代码喜欢下面
import UIKit
class SepetCell: UITableViewCell{
@IBOutlet var barcode: UILabel!
@IBOutlet var name: UILabel!
@IBOutlet var fav: UIButton!
@IBOutlet var strep: UIStepper!
@IBOutlet var times: UILabel!
@IBAction func favoriteClicked(sender: UIButton) {
println(sender.tag)
println(times.text)
SepetViewController().favorite(sender.tag)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
字符串
这是我的xib文件背后的代码为. swift。
在主页面的代码喜欢下面:
import UIKit
import CoreData
class SepetViewController: UIViewController, UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate {
@
IBOutlet
var sepetTable: UITableView!
var barcodes: [CART] = []
let managedObjectContext = (UIApplication.sharedApplication().delegate as!AppDelegate).managedObjectContext
override func viewWillAppear(animated: Bool) {
if let moc = self.managedObjectContext {
var nib = UINib(nibName: "SepetTableCell", bundle: nil)
self.sepetTable.registerNib(nib, forCellReuseIdentifier: "productCell")
}
fetchLog()
sepetTable.reloadData()
}
func fetchLog() {
if let moc = self.managedObjectContext {
barcodes = CART.getElements(moc);
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) - > Int {
return self.barcodes.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) - > UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("productCell") as ? SepetCell
if cell == nil {
println("cell nil")
}
let product: CART
product = barcodes[indexPath.row]
cell!.barcode ? .text = product.barcode
cell!.name ? .text = product.name
cell!.fav.tag = indexPath.row
return cell!
}
func favorite(tag: Int) {
}
}
型
当我点击最喜欢的按钮内的细胞。例如,我想将时间标签文本更改为任何内容。
当我点击fav按钮时,事件将转到SepetCell。swift favoriteClicked(sender:UIButton)功能。
所以如果我试着打电话:SepetViewController().favorite(sender.tag)
它将进入
func favorite(tag: Int) {
sepetTable.reloadData()
}
型
但是sepetTable在那里时为nil。我想这是因为当我调用这个SepetViewController().favorite(sender.tag)函数时。它首先创建SepetViewController类。因此,由于对象未设置,它将变为null。
我如何才能到达那个sepetTable或者解决这个问题的最佳方法是什么。
- 谢谢-谢谢
5条答案
按热度按时间vcudknz31#
解决这个问题的常用模式是闭包和委托。如果您想使用闭包,可以执行如下操作:
字符串
然后,
型
然后在您的tableview委派中:
型
另一种流行的方法是使用委托模式:
型
然后,
型
..现在在您的视图控制器中:
然后在您的tableview委派中:
型
并将一致性添加到协议中,如下所示:
型
希望这对你有帮助!
xyhw6mcr2#
上面所有的图案都很好。我的两分钱,如果你添加代码(例如多个不同的细胞等..)有一个FAR简单的解决方案。
由于按钮允许指定一个“目标”您可以直接传递控制器和操作到单元格/按钮时设置它。
在控制器中:
字符串
...
在带有按钮自定义单元格中:
型
svmlkihl3#
为该按钮添加目标。
字符串
设置该按钮的标签,因为您正在使用它。
型
通过子类化UITableViewCell来实现这一点。按钮,通过插座连接。
要获取连接函数中的标记:
型
3wabscal4#
字符串
一月一日
型
l0oc07j25#
凌晨2点回答:你想太多了。创建自定义TableViewCell类;将原型单元类设置为新的自定义类;然后创建IBAction。