๐Ÿ“ฑ App Development Study/iOS๐ŸŽ

[Udemy iOS & Swift Bootcamp] ์ฑ„ํŒ… ์™„์„ฑํ•˜๊ธฐ 2 (์ตœ์‹  ๋ฉ”์„ธ์ง€(๋งจ ์•„๋ž˜)์œผ๋กœ ํ™”๋ฉด ์Šคํฌ๋กคํ•˜๊ธฐ.)

ibelieveinme 2023. 7. 4. 23:51
728x90

2. ์ตœ์‹  ๋ฉ”์„ธ์ง€(๋งจ ์•„๋ž˜)์œผ๋กœ ํ™”๋ฉด ์Šคํฌ๋กคํ•˜๊ธฐ.

 

์ฑ„ํŒ…์„ ์ž‘์„ฑํ–ˆ์„ ๋•Œ, ํ™”๋ฉด ์Šคํฌ๋กค์„ ๋งจ ์•„๋ž˜๋กœ ๋‚ด๋ ค์„œ ์ตœ์‹  ๋ฉ”์„ธ์ง€๋ฅผ ๋ณด์—ฌ์ค˜์•ผ ํ•œ๋‹ค.

 

tableView ์—์„œ ํŠน์ • ์…€๋กœ ์Šคํฌ๋กค ํ•˜๋Š” ํ•จ์ˆ˜๋Š” scrollToRow ํ•จ์ˆ˜ ์ด๋‹ค.

ํŠน์ •์…€ ์ธ๋ฑ์Šค์ธ indexPath, ์Šคํฌ๋กค ํฌ์ง€์…˜(top, bottom, middle), ์Šคํฌ๋กค ์• ๋‹ˆ๋ฉ”์ด์…˜ ํšจ๊ณผ true or false ์ธ์ž๊ฐ€ ๋“ค์–ด๊ฐ„๋‹ค.

 

    func loadMessages(){
        db.collection(K.FStore.collectionName).order(by: K.FStore.dateField).addSnapshotListener { (querySnapshot, err) in
            
            self.messages = []
            
            if let e = err {
                print("Error getting documents: \(e)")
            } else {
                    for doc in querySnapshot!.documents {
                        let data = doc.data()
                        if let messageSender = data[K.FStore.senderField] as? String,
                           let messageBody = data[K.FStore.bodyField] as? String {
                            let newMessage = Message(sender: messageSender, body: messageBody)
                            self.messages.append(newMessage)
                            
                            DispatchQueue.main.async{
                                self.tableView.reloadData()
                                
                                let indexPath = IndexPath(row: self.messages.count - 1, section: 0)
                                self.tableView.scrollToRow(at: indexPath, at: .top, animated: true)
                                
                            }
                        }
                    }
            }
        }
    }

ChatViewController ํด๋ž˜์Šค์˜ loadmessages() ํ•จ์ˆ˜์—์„œ tableView์— ๋ฐ์ดํ„ฐ๋ฅผ reload ํ•˜๋Š” ๋ถ€๋ถ„์— tableView๋ฅผ ์Šคํฌ๋กค ํ•˜๋Š” ์ฝ”๋“œ๋ฅผ ์ถ”๊ฐ€ํ•ด์ฃผ์—ˆ๋‹ค.

 

์ด ๋•Œ, indexPath ๊ฐ’์„ ๊ตฌํ•˜๊ธฐ ์œ„ํ•ด indexPath ๋ณ€์ˆ˜๋ฅผ ๋งŒ๋“ค์—ˆ๋‹ค. ๋ฉ”์„ธ์ง€ ๊ฐœ์ˆ˜ - 1 ์ธ๋ฑ์Šค ๋ฐ 0 ์„ธ์…˜์„ ๊ฐ€๋ฆฌํ‚จ๋‹ค.

 

 

๊ฒฐ๊ณผํ™”๋ฉด์€ ์•„๋ž˜์™€ ๊ฐ™๋‹ค.

728x90