gpt4 book ai didi

swift - 在 UITableView Swift 中使用 bool 值切换按钮

转载 作者:行者123 更新时间:2023-11-28 14:09:45 24 4
gpt4 key购买 nike

我想添加一个 bool 切换以了解按钮是否已被按下(会将此值保存到核心数据(如果为真,还想将单元格数据保存到核心数据,如果为假,则从核心数据中删除))我我不知道该怎么做。任何帮助将不胜感激。如果需要来自 View Controller 的所有代码,请发表评论,我会这样做(我已经设置了 xcdatamodel)。

  @IBAction func buttonTapped(_ sender:UIButton) {
var superView = sender.superview
while !(superView is UITableViewCell) {
superView = superView?.superview
}
let cell = superView as! UITableViewCell
if let indexpath = tableView.indexPath(for: cell){

print(indexpath)
}
}

最佳答案

好吧,我构建了一个简单的项目,并使用协议(protocol)解决了一些问题,首先你定义一个这样的协议(protocol):

protocol cellDidRequestSaving {
func saveOrDelete(indexpath : Int)
}

首先在你的单元格中定义你这样的按钮:

class TableViewCell: UITableViewCell {
var delegate: cellDidRequestSaving?
var indexPath = 0 //come from the parent
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
}

@IBAction func didTap(_ sender: Any) {
// this protocol defined in the parent
delegate?.saveOrDelete(indexpath: indexPath)

}
}

现在在你的 tableViewController 中你使用这样的协议(protocol):

 class TableViewController: UITableViewController, cellDidRequestSaving {
var cellStat = [Int:Bool]()
override func viewDidLoad() {
super.viewDidLoad()

// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false

// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 3
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
cell.indexPath = indexPath.row
cell.delegate = self
// Configure the cell...

return cell
}
func saveOrDelete(indexpath: Int) {
if let status = cellStat[indexpath], status {
print(indexpath, "delete")
cellStat[indexpath] = !status
}
else {
print(indexpath, "save")
cellStat[indexpath] = true
}
}

这是一个简单的项目,但您可以了解如何去做。另外,请注意协议(protocol)定义和用法,这样您就不会错过任何东西。输出是这个 Out Put of The Project

关于swift - 在 UITableView Swift 中使用 bool 值切换按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52686867/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com