私は基本的な配列を表すテーブルビューを持っています。セルには、配列のpercentage
プロパティの値を示すラベルとスライダがあります。基本的な配列要素の変更に基づいてKVOを使用してtableViewCellを更新する方法
パーセンテージのプロパティが変更されるたびに、キー値の観測を使用してラベルを更新したいと考えています。 (私はKVOがこの例では残虐であることを知っていますが、最終的にスライダをスライドさせるとスライダの位置を含む他のセルに影響を及ぼし、その下にある配列はアプリケーションの複数の場所から設定されますので、いつでもKVOが行く方法です。 )
私は助けをたくさん持っていましたfrom this answer、私はそれを発射し、ラベルを更新することはできません。私はここにすべてのコードを含めています。どこが間違っているのか分かりません。
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, CustomCellDelegate {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
for i in 0...4 {
items.append(Items(ID: i, percentage: 50))
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: myTableViewCell.ID) as? myTableViewCell {
cell.object = items[indexPath.row]
cell.mySlider.tag = indexPath.row
return cell
} else {
return UITableViewCell()
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
@IBAction func sliderValueChanged(_ sender: UISlider) {
items[sender.tag].percentage = Double(sender.value)
print("percentage at \(items[sender.tag].ID) is \(items[sender.tag].percentage)")
}
func didUpdateObject(for cell: UITableViewCell) {
if let indexPath = tableView.indexPath(for: cell) {
tableView.reloadRows(at: [indexPath], with: .automatic)
print("hello")
}
}
}
class myTableViewCell: UITableViewCell {
static let ID = "myCell"
weak var delegate: CustomCellDelegate?
private var token: NSKeyValueObservation?
var object: Items? {
willSet {
token?.invalidate()
}
didSet {
myLabel.text = "\(object?.percentage ?? 0)"
token = object?.observe(\.percentage) { [weak self] object, change in
if let cell = self {
cell.delegate?.didUpdateObject(for: cell)
}
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
}
@IBOutlet weak var myLabel: UILabel!
@IBOutlet weak var mySlider: UISlider!
}
class Items: NSObject {
let ID: Int
@objc dynamic var percentage: Double
init(ID: Int, percentage: Double){
self.ID = ID
self.percentage = percentage
super.init()
}
}
var items: [Items] = []
protocol CustomCellDelegate: class {
func didUpdateObject(for cell: UITableViewCell)
}
ありがとうございます@Rob。私はその事例を私の実装に取り入れています。そして、私はほとんどそれを取得します。それは完全にそれをgrokするためにそれ以上行くだろう。本当に助けていただきありがとうございます!スイフトはあなたと強いです。 – Sean
[working](https://imgur.com/a/dyGtX) – Sean