如何在swift?中将结构模型中的数据从第二个ViewController追加到第一个ViewController,并重新加载第一个VC中存在的tableView?

jutyujz0  于 2022-11-21  发布在  Swift
关注(0)|答案(3)|浏览(154)

//我有Notes的结构模型

struct NotesModel{
    
    var groupName: String // sections in tableView
    var info: [NotesInfo] // rows in respective sections in tableView
    
}

struct NotesInfo{
    
    var groupName: String
    var image: String
    var notesTitle: String
    var notesDescription: String
    var notesDate: String
    
}

// 1) this is my ViewController(FirstVC)

var arrayNotes = [NotesModel]() // array that will be used to populate tableView
var info1 = [NotesInfo]()
var info2 = [NotesInfo]()
var info3 = [NotesInfo]()

// I have appended data in arrayNotes

info1.append(NotesInfo(groupName: "ABC", image: "img1", notesTitle: "Public Notes", notesDescription: "Public Notes are for xyz use...", notesDate: "17/08/2020"))

info1.append(NotesInfo(groupName: "ABC", image: "img1", notesTitle: "Public Notes(A)", notesDescription: "Public Notes are for xyz use...", notesDate: "19/08/2020"))
        
arrayNotes.append(NotesModel(groupName: "ABC", info: info1))

info2.append(NotesInfo(groupName: "XYZ", image: "img2", notesTitle: "My Notes", notesDescription: "My Notes include...", notesDate: "25/08/2020"))

arrayNotes.append(NotesModel(groupName: "XYZ", info: info2))        
        
info3.append(NotesInfo(groupName: "PQR", image: "img3", notesTitle: "Notes Example", notesDescription: "Notes Example here..", notesDate: "25/08/2020"))
       
arrayNotes.append(NotesModel(groupName: "PQR", info: info2))

// I have a TableView on ViewController to present NotesModel data

// MARK: - Number of Sections in TableView
    
    func numberOfSections(in tableView: UITableView) -> Int {
        
        return arrayNotes.count // returns 3
        
    }

// MARK: - HeaderView in Section
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
                
        let headerCell = Bundle.main.loadNibNamed("HeaderCell", owner: self, options: nil)?.first as! HeaderCell
        
        let dict = arrayNotes[section]
        headerCell.lblGroupName.text = dict.groupName // "ABC", "XYZ", "PQR"

        let info = dict.info

        for values in  info{

            headerCell.imgGroup.image = UIImage(named: values.image) // "img1", "img2", "img3"
        }        
        return headerCell
        
    }

// MARK: - Number of Rows in TableView
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return arrayNotes[section].info.count // "ABC" -> 2 rows, "XYZ" -> 1 row, "PQR" -> 1 row
    }

// MARK: - Cell For Row At in TableView
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "NotesCell", for: indexPath) as! NotesCell
        
        cell.selectedBackgroundView = UIView()
        cell.selectedBackgroundView?.backgroundColor = .systemBackground
                
        let dict = arrayNotes[indexPath.section]

        let info = dict.info[indexPath.row]
        
        cell.lblNotesTitle.text = info.notesTitle
        cell.lblNotesDescription.text = info.notesDescription
        cell.lblNotesDate.text = info.notesDate
        
        return cell
        
    }

// MARK: - Button Create New Note Event

 func createNewNotesButton(_ sender: UIButton){
        
        let storyBoard = UIStoryboard(name: "NotesStoryBoard", bundle: nil)
        
        let createNewNotesVC = storyBoard.instantiateViewController(withIdentifier: "CreateNewNotesVC") as! CreateNewNotesVC
        createNewNotesVC.delegate = self
        
        self.navigationController?.pushViewController(createNewNotesVC, animated: true)
        
    }

// MARK: - Create New Notes Protocol Conformance
    
    func passNewNotesModel(object: NotesModel) {
                
        for item in arrayNotes{
            if item.groupName == object.groupName{
                print("same section")
                var ogInfo = item.info
                let addedInfo = object.info
                
                ogInfo.append(contentsOf: addedInfo)
                print("ogInfo after appending --> \(ogInfo)")
                
                arrayNotes.append(NotesModel(groupName: item.groupName, info: ogInfo)) 

// I want to append rows in section that already exist on ViewController, there is already 3 sections with different number of rows but this doesn't append in respective section but creates new section every time

            }else{
                print("different section")

                arrayNotes.append(object) 

// and if section doesn't exist here on ViewController then create new section and add rows in it. but this adds multiple sections

            }
        }
        
        self.tableViewNotes.reloadData()
        
    }

1.这是我创建新笔记VC(第二个VC)
// MARK:-通信协定为NotesModel建立新的Notes
协议创建新的笔记模型{ func passNewNotesModel(对象:备注型号)}
var新笔记型号:备注模型!
变量代理:是否创建新Notes模型?
这里我有textFields和“SUBMIT”按钮,在单击“SUBMIT”按钮时,将NotesModel对象和popView传递给firstVC,firstVC上tableView应该使用新创建的模型对象进行更新。
这里还有一个下拉菜单,我必须从中选择注解的组名。例如,有6个不同的组名,它们代表tableView中的部分。如果我从下拉菜单中选择“ABC”组名,然后在ViewController上如果我从下拉列表中选择“OMG”组名,而ViewController上不存在该组名,则(firstVC)数据应追加到tableView中“ABC”部分(firstVC),则应创建新的节。

// MARK: - Button Submit Event

@IBAction func btnSubmit_Event(\_ sender: Any) {

var info = [NotesInfo]()

info.append(NotesInfo(groupName: txtSelectGroup.text ?? "", image: ImageString, notesTitle: txtNotesTitle.text ?? "", notesDescription: txtNotesDescription.text ?? "", notesDate: txtNotesDate.text ?? ""))
    
    newNotesModel = (NotesModel(groupName: txtSelectGroup.text ?? "", info: info))

    delegate?.passNewNotesModel(object: newNotesModel)
    
    self.navigationController?.popViewController(animated: true)

   }

我想在各自的部分追加数据,我的代码是生成部分每次由于循环,我不知道如何追加数据在各自的部分,任何帮助将是非常感谢!谢谢。

// UPDATE: as per WeyHan Ng suggestion:

for item in arrayNotes{
            var ogInfo = item.info
            let addedInfo = object.info

            ogInfo.append(contentsOf: addedInfo)
            print("ogInfo after appending --> \(ogInfo)")

            if item.groupName == object.groupName{

                print("same section")

                let index = arrayNotes.firstIndex(where: { $0.groupName == object.groupName})!
                print(index)

                arrayNotes[index].info = ogInfo // this is solved

            }else{
                print("different section")
                arrayNotes.append(object) // ISSUE: appending more than one section every time
            }

        }

        self.tableViewConsultantMilestones.reloadData()
f4t66c6m

f4t66c6m1#

根据passNewNotesModel(object: newNotesModel)方法中的代码,您将执行以下操作:

Iterate through every element in 'arrayNotes' as 'item'.
  If the element 'groupName' of 'item' matches the 'groupName' of 'object'
    Make a copy of 'item.info' as 'ogInfo'
    Make a copy of 'object.info' as 'addedInfo'

    Append 'addedInfo' to 'ogInfo'

    Append 'ogInfo' to 'arrayNotes'

  Else
    Append 'object' to 'arrayNotes'
  End if
End loop

因此,对于具有N个元素的arrayNotes,您的代码追加N-1次object,并追加1次ogInfo + addedInfo
你需要做的是:

Find index of the element with 'groupName' equal to 'object.groupName'
If found
  Replace 'arrayNotes[foundIndex]' with 'arrayNotes[foundIndex] + object.info'

Else
  Append 'object' to 'arrayNotes'
End if

提示:可以使用first(where: (String) throws -> Bool)方法在arrayNotes中找到元素,并使用其返回值替换该元素。

qyzbxkaa

qyzbxkaa2#

//更新
//以下代码对我有效

// MARK: - Create New Notes Protocol Conformance

func passNewNotesModel(object: NotesModel) {

let filteredDict = self.arrayNotes.filter({$0.groupName == object.groupName})

if filteredDict.count > 0 {
    
    // add rows in that particular section
    
    for indexValue in arrayNotes.enumerated() {
        
        if indexValue.element.groupName == filteredDict.first?.groupName {
            
            if let obj = filteredDict.first {
                
                var ogInfo = obj.info
                let addedInfo = object.info
                ogInfo.append(contentsOf: addedInfo)
                arrayNotes[indexValue.offset].info = ogInfo
                
            }
            
        }
        
    }
    
} else {
    
    // add new section
    arrayNotes.append(object)
    
}

}
bt1cpqcv

bt1cpqcv3#

//更新
// WeyHan Ng的建议对我起了作用:

// MARK: - Create New Notes Protocol Conformance

 func passNewNotesModel(object: NotesModel) {

let index = arrayNotes.firstIndex(where: { $0.groupName == object.groupName})
print(index ?? 0)

if index != nil{
    var ogInfo = arrayNotes[index ?? 0].info
    let addedInfo = object.info
    ogInfo.append(contentsOf: addedInfo)
    arrayNotes[index ?? 0].info = ogInfo
}else{
    arrayNotes.append(object)
}

}

相关问题