gpt4 book ai didi

ios - 如何将步进值传递给 ViewController?

转载 作者:行者123 更新时间:2023-12-01 19:29:29 25 4
gpt4 key购买 nike

我有一个自定义单元格,它有 2 个标签,myLabel 和 numLabel,以及一个步进器。我在 Swift 文件和 XIB 文件中有我的自定义单元格。我希望当我单击步进器上的 + 或 - 按钮时,我的 numLabel 会随着步进器的值而变化。我不知道如何将步进值传递给我有 tableView 的 viewController。后来想将步进值保存到 CoreDate 我该怎么做?我只是一个初学者。谢谢你的帮忙。
MyCell.swift

import UIKit

class MyCell: UITableViewCell {

static let identifier = "MyCell"

static func nib() -> UINib {
return UINib(nibName: "MyCell", bundle: nil)
}

public func configure(with name: String, number: String) {
myLabel.text = name
numLabel.text = number
}

@IBOutlet var myLabel: UILabel!
@IBOutlet var numLabel: UILabel!



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
}

}
ViewController.swift
import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet var table: UITableView!

override func viewDidLoad() {
super.viewDidLoad()
table.register(MyCell.nib(), forCellReuseIdentifier: MyCell.identifier)
table.delegate = self
table.dataSource = self
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: MyCell.identifier, for: indexPath) as! MyCell
cell.configure(with: "Item 1", number: "1")
return cell
}


}
My Screen Shot

最佳答案

您可以使用“回调”闭包轻松完成此操作:

class MyCell: UITableViewCell {
static let identifier: String = "MyCell"

@IBOutlet var myStepper: UIStepper!
@IBOutlet var numLabel: UILabel!
@IBOutlet var myLabel: UILabel!

// "callback" closure - set my controller in cellForRowAt
var callback: ((Int) -> ())?

public func configure(with name: String, number: String) {
myLabel.text = name
numLabel.text = number
}

@IBAction func stepperChanged(_ sender: UIStepper) {
let val = Int(sender.value)
numLabel.text = "\(val)"
// send value back to controller via closure
callback?(val)
}

static func nib() -> UINib {
return UINib(nibName: "MyCell", bundle: nil)
}

}
然后,在 cellForRowAt :
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: MyCell.identifier, for: indexPath) as! MyCell
cell.configure(with: "Item 1", number: "1")

// set the "callback' closure
cell.callback = { (val) in
print("Stepper in cell at \(indexPath) changed to: \(val)")
// do what you want when the stepper value was changed
// such as updating your data array
}

return cell
}

关于ios - 如何将步进值传递给 ViewController?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63816531/

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