gpt4 book ai didi

ios - 如何使用字典中的值保持按钮状态

转载 作者:行者123 更新时间:2023-11-28 13:40:39 25 4
gpt4 key购买 nike

我有一个 UITableView 从带有标签的字典中填充。用户可以将标签从一个 ViewController 添加到另一个 ViewController。每个标签都有一个属性 remoteID。当用户按下 + 按钮添加标签时,所选标签的按钮颜色会更改为 -。到目前为止一切正常。问题是当我从 MainViewController 返回到 TagsViewController 时,按钮的状态没有保存。现在所有标签按钮显示+。你能帮我保存按钮的状态(标题)吗?在这里,我创建了一个小项目来解决我的问题:https://github.com/tygruletz/AppendTagsToCells这是我的代码:

class Tag{

var remoteID: Int
var categoryID: Int
var name: String
var color: String
init(remoteID: Int, categoryID: Int, name: String, color: String) {
self.remoteID = remoteID
self.categoryID = categoryID
self.name = name
self.color = color
}
}

主VC:

class ChecklistVC: UIViewController {

@IBOutlet weak var questionsTableView: UITableView!

//Properties
lazy var itemSections: [ChecklistItemSection] = {
return ChecklistItemSection.checklistItemSections()
}()
var lastIndexPath: IndexPath!

override func viewDidLoad() {
super.viewDidLoad()
}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
questionsTableView.reloadData()
}
}

extension ChecklistVC: UITableViewDelegate, UITableViewDataSource {

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

let itemCategory = itemSections[section]
return itemCategory.checklistItems.count
}

func numberOfSections(in tableView: UITableView) -> Int {

return itemSections.count
}

// Set the header of each section
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

let checklistItemCategory = itemSections[section]
return checklistItemCategory.name.uppercased()
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: "checklistCell", for: indexPath) as! ChecklistCell

let itemCategory = itemSections[indexPath.section]
let item = itemCategory.checklistItems[indexPath.row]
cell.delegate = self
cell.configCell(item)

cell.vehicleCommentLabel.text = item.vehicleComment
cell.trailerCommentLabel.text = item.trailerComment

let sortedTagNames = item.vehicleTags.keys.sorted(by: {$0 < $1}).compactMap({ item.vehicleTags[$0]})

print("Sorted tag names: \(sortedTagNames.map {$0.name})")

let joinedTagNames = sortedTagNames.map { $0.name}.joined(separator: ", ")

cell.tagNameLabel.text = joinedTagNames

return cell
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

return 150
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

if segue.identifier == "goChecklistAddComment" {
let addCommentVC = segue.destination as! ChecklistAddCommentVC
addCommentVC.delegate = self
}

if segue.identifier == "goChecklistAddTag" {
let addTagVC = segue.destination as! ChecklistAddTagVC
addTagVC.delegate = self
addTagVC.addedTags = itemSections[lastIndexPath.section].checklistItems[lastIndexPath.row].vehicleTags
}
}
}

// Receive Tags from ChecklistAddTagVC using the Delegate Pattern
extension ChecklistVC: ChecklistAddTagVCDelegate{

func receiveAddedTags(tags: [Int : Tag]) {

let item = self.itemSections[self.lastIndexPath.section].checklistItems[self.lastIndexPath.row]
item.vehicleTags = tags
}
}

标签VC:

protocol ChecklistAddTagVCDelegate {
func receiveAddedTags(tags: [Int: Tag])
}

class ChecklistAddTagVC: UIViewController {

// Interface Links
@IBOutlet weak var tagsTableView: UITableView!

// Properties
var tagsDictionary: [Int: Tag] = [:]
var addedTags: [Int: Tag] = [:]
var delegate: ChecklistAddTagVCDelegate?
var indexPathForBtn: IndexPath!

override func viewDidLoad() {
super.viewDidLoad()
tagsTableView.tableFooterView = UIView()

tagsDictionary = [
1: Tag(remoteID: 1, categoryID: 1, name: "Tag1", color: "red"),
2: Tag(remoteID: 2, categoryID: 1, name: "Tag2", color: "blue"),
3: Tag(remoteID: 3, categoryID: 1, name: "Tag3", color: "orange"),
4: Tag(remoteID: 4, categoryID: 1, name: "Tag4", color: "black")
]
}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)

print("Added tags: \(addedTags.map {$1.name})")

setupButtons()

tagsTableView.reloadData()
}
}

extension ChecklistAddTagVC: UITableViewDelegate, UITableViewDataSource {

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "defectAndDamageTagCell", for: indexPath) as! ChecklistAddTagCell
cell.configCell()
cell.delegate = self
cell.tagNameLabel.text = tagsDictionary[indexPath.row + 1]?.name.capitalized
indexPathForBtn = indexPath

return cell
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

return 60
}
}

extension ChecklistAddTagVC: ChecklistAddTagCellDelegate{

// When the user press Add Tag then will be added in a dictionary and sent to ChecklistVC using a callback closure.
func addTagBtnPressed(button: UIButton, tagLabel: UILabel) {

let buttonPosition: CGPoint = button.convert(CGPoint.zero, to: tagsTableView)
let indexPath = tagsTableView.indexPathForRow(at: buttonPosition)
let indexPathForBtn: Int = indexPath?.row ?? 0
let tag: Tag = tagsDictionary[indexPathForBtn + 1] ?? Tag(remoteID: 0, categoryID: 0, name: String(), color: String())

if button.currentTitle == "+"{
button.setTitle("-", for: UIControl.State.normal)
tagLabel.textColor = UIColor.orange

// Add selected tag to Dictionary when the user press +
addedTags[tag.remoteID] = tag
}
else{
button.setTitle("+", for: UIControl.State.normal)
tagLabel.textColor = UIColor.black

// Delete selected tag from Dictionary when the user press -
addedTags.removeValue(forKey: tag.remoteID)
}
// Send the Dictionary to ChecklistVC
if delegate != nil{
delegate?.receiveAddedTags(tags: addedTags)
}
print("\n ****** UPDATED DICTIONARY ******")
print(addedTags.map {"key: \($1.remoteID) - name: \($1.name)"})
}

// Setup the state of the buttons and also the color of the buttons to be orange if that Tag exist in `addedTags` dictionary.
func setupButtons(){

for eachAddedTag in addedTags {

if eachAddedTag.value.remoteID == tagsDictionary[1]?.remoteID {

print(eachAddedTag)
}
}
}
}

这是我的错误捕获:

enter image description here

感谢您正在阅读本文!

最佳答案

首先你需要一个数组而不是字典

tagsArr = [
Tag(remoteID: 1, categoryID: 1, name: "Tag1", color: "red"),
Tag(remoteID: 2, categoryID: 1, name: "Tag2", color: "blue"),
Tag(remoteID: 3, categoryID: 1, name: "Tag3", color: "orange"),
Tag(remoteID: 4, categoryID: 1, name: "Tag4", color: "black")
]

然后 vehicleTags propety 应该是 [Tag]() ,知道它是否存在使用 ChecklistAddTagVC 的 cellForRowAt 里面

let tag = tagsArr[indexPath.row].remoteID
let res = addedTags.map { $0.remoteID }

if res.contains(tag) {
// tag exists color it
}
else {
// not here
}

关于ios - 如何使用字典中的值保持按钮状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56080470/

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