В iOS 26 Observable получил новое обновление, где Uikit может освежить себя, когда изменяется зависимый наблюдаемый объект. К сожалению, я не могу выяснить, почему мой WordtableViewController не перезаряжает и не показывает новые элементы, когда я добавляю. < /P>
@Observable
@MainActor
class Word {
var value: String
init(value: String) {
self.value = value
}
}
class WordTableViewController: UITableViewController {
var words = [Word(value: "First"), Word(value: "Second"), Word(value: "Third")]
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "Refresh",
style: .plain,
target: self,
action: #selector(refreshWords)
)
}
@objc private func refreshWords() {
words.append(Word(value: "John Doe"))
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
words.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
var content = cell.defaultContentConfiguration()
content.text = words[indexPath.row].value
cell.contentConfiguration = content
return cell
}
}
< /code>
Согласно статьям, которые я прочитал, должны автоматически перезагрузить и показывать новые ячейки, когда какие -либо новые данные добавляются в массив слов. В статье они использовали uicollectionView, и я использую uitableview. < /P>
Обновление: использование uicollectionView < /p>
@Observable
class CustomerStore {
var customers = [Customer(name: "John Doe"), Customer(name: "Mary Doe")]
}
class CustomerCollectionViewController: UICollectionViewController {
let store = CustomerStore()
init() {
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: UIScreen.main.bounds.width - 32, height: 60)
layout.sectionInset = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)
layout.minimumLineSpacing = 12
super.init(collectionViewLayout: layout)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "CollectionViewCell")
self.title = "Customers"
self.navigationController?.navigationBar.prefersLargeTitles = true
// add a button on the bar
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Update", style: .plain, target: self, action: #selector(updateCustomer))
}
@objc private func updateCustomer() {
store.customers[0].name = "Steven Smith"
print(store.customers)
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
store.customers.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath)
cell.configurationUpdateHandler = { [weak self] cell, state in
var content = UIListContentConfiguration.cell()
content.text = self?.store.customers[indexPath.row].name
cell.contentConfiguration = content
}
return cell
}
}
Подробнее здесь: https://stackoverflow.com/questions/796 ... controller
IOS 26 UIKIT и наблюдаемые с UitableViewController ⇐ IOS
Программируем под IOS
-
Anonymous
1751383280
Anonymous
В iOS 26 Observable получил новое обновление, где Uikit может освежить себя, когда изменяется зависимый наблюдаемый объект. К сожалению, я не могу выяснить, почему мой WordtableViewController не перезаряжает и не показывает новые элементы, когда я добавляю. < /P>
@Observable
@MainActor
class Word {
var value: String
init(value: String) {
self.value = value
}
}
class WordTableViewController: UITableViewController {
var words = [Word(value: "First"), Word(value: "Second"), Word(value: "Third")]
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "Refresh",
style: .plain,
target: self,
action: #selector(refreshWords)
)
}
@objc private func refreshWords() {
words.append(Word(value: "John Doe"))
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
words.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
var content = cell.defaultContentConfiguration()
content.text = words[indexPath.row].value
cell.contentConfiguration = content
return cell
}
}
< /code>
Согласно статьям, которые я прочитал, должны автоматически перезагрузить и показывать новые ячейки, когда какие -либо новые данные добавляются в массив слов. В статье они использовали uicollectionView, и я использую uitableview. < /P>
Обновление: использование uicollectionView < /p>
@Observable
class CustomerStore {
var customers = [Customer(name: "John Doe"), Customer(name: "Mary Doe")]
}
class CustomerCollectionViewController: UICollectionViewController {
let store = CustomerStore()
init() {
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: UIScreen.main.bounds.width - 32, height: 60)
layout.sectionInset = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)
layout.minimumLineSpacing = 12
super.init(collectionViewLayout: layout)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "CollectionViewCell")
self.title = "Customers"
self.navigationController?.navigationBar.prefersLargeTitles = true
// add a button on the bar
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Update", style: .plain, target: self, action: #selector(updateCustomer))
}
@objc private func updateCustomer() {
store.customers[0].name = "Steven Smith"
print(store.customers)
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
store.customers.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath)
cell.configurationUpdateHandler = { [weak self] cell, state in
var content = UIListContentConfiguration.cell()
content.text = self?.store.customers[indexPath.row].name
cell.contentConfiguration = content
}
return cell
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79683427/ios-26-uikit-and-observables-with-uitableviewcontroller[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия