๐Ÿ’Œ๋ฉ”์„ธ์ง€์ž‘์„ฑ ์‹œ์ž‘, ์™„๋ฃŒ์‹œ ๋ฐ‘์œผ๋กœ๐Ÿ‘‡ ์Šคํฌ๋กค

8196 ๋‹จ์–ด swiftuiswiftFirebaseFirebase

๐Ÿ‘†๐Ÿ‘‡ScrollViewReader?

Apple Developer Documentation - ScrollViewReader

ScrollViewReader๋ž€ ํ”„๋ก์‹œ๋ฅผ ์ด์šฉํ•ด ์ž์‹ ๋ทฐ๋กœ ์Šคํฌ๋กคํ•˜๊ธฐ ์œ„ํ•ด ํ”„๋กœ๊ทธ๋ž˜๋งคํ‹ฑํ•œ ์Šคํฌ๋กค์„ ์ œ๊ณตํ•˜๋Š” ๋ทฐ์ด๋‹ค. ์Šคํฌ๋กค๋ทฐ๋ฅผ ์Šคํฌ๋กค๋ฆฌ๋”๋กœ ๊ฐ์‹ผ๋‹ค.

ScrollViewReader { proxy in
    ScrollView {
        ...
    }
}

@Namespace

@Namespace๋ฅผ ์ด์šฉํ•ด id๋ฅผ ๋ถ€์—ฌํ•œ๋‹ค.

@Namespace var topID
@Namespace var bottomID

์Šคํฌ๋กค ์‹œ์ž‘์ , ๋์  ์ง€์ •ํ•˜๊ธฐ

์Šคํฌ๋กค์˜ ์œ—๋ถ€๋ถ„์—๋Š” ๋ฐ‘์„ ๊ฐ€๋ฆฌํ‚ค๋Š” ํ™”์‚ดํ‘œ chevron ๋ฒ„ํŠผ์„ ๋งŒ๋“ค์—ˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ๋ฒ„ํŠผ์ด ๋ˆŒ๋ฆฌ๋ฉด bottomId๋ฅผ ๊ฐ€์ง„ ๋ทฐ๋กœ ์Šคํฌ๋กคํ•˜๊ฒŒ ํ•˜์˜€๋‹ค. ๋ฐ˜๋Œ€๋กœ ์Šคํฌ๋กค์˜ ๋ฐ‘์—๋Š” ํ•˜๋‹จ ์Šคํฌ๋กค์˜ ์œ„์น˜๊ฐ’์„ ์–ป๊ธฐ ์œ„ํ•ด ๋นˆ HStack์„ ์ถ”๊ฐ€ํ•˜์˜€๋‹ค.

ScrollViewReader { proxy in
    ScrollView {
        Button(
            action: { withAnimation { proxy.scrollTo(bottomID) } },
            label: { Image(systemName: "chevron.down").foregroundColor(Color(.systemGray2)) })
            .id(topID)
        
        ...
        
        HStack {}.id(bottomID)
    }
}

๐Ÿ’Œ๋ฉ”์„ธ์ง€ ์ž‘์„ฑ ์‹œ์ž‘, ์™„๋ฃŒ ํ™•์ธ

๋ฉ”์„ธ์ง€๊ฐ€ ์ž‘์„ฑ๋˜๋ฉด messageText์— ์ €์žฅ๋œ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ๋ฉ”์„ธ์ง€๋ฅผ ๋ณด๋‚ด๋ฉด ๋นˆ ๋ฌธ์ž์—ด์ด ๋˜๋„๋ก ๋ฏธ๋ฆฌ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•˜์˜€๋‹ค.

@State private var messageText = ""

๋ฉ”์„ธ์ง€ ์ฒซ๊ธ€์ž๋ฅผ ์ž…๋ ฅํ–ˆ์„ ๋•Œ messageText๋Š” ๋นˆ ๋ฌธ์ž์—ด์—์„œ ๊ธธ์ด๊ฐ€ ์žˆ๋Š” ๋ฌธ์ž์—ด๋กœ ๋ฐ”๋€๋‹ค. ๊ทธ๋ฆฌ๊ณ  ๋ฉ”์„ธ์ง€๋ฅผ ๋ณด๋‚ด๋ฉด ๊ธธ์ด๊ฐ€ ์žˆ๋Š” ๋ฌธ์ž์—ด์—์„œ ๋นˆ ๋ฌธ์ž์—ด๋กœ ๋ณ€ํ™”ํ•œ๋‹ค. ์ด ๋ณ€ํ™”์— ๋”ฐ๋ผ ์Šคํฌ๋กค์„ ๋ฐ‘์œผ๋กœ ๋‚ด๋ฆฌ๋Š” ์• ๋‹ˆ๋ฉ”์ด์…˜์„ ์‹คํ–‰ํ•œ๋‹ค. onChange ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ–ˆ๊ณ , messageText == "" Bool๊ฐ’ ๋ณ€ํ™”์— ๋”ฐ๋ผ ์Šคํฌ๋กค์„ ๋‚ด๋ฆฌ๋„๋ก ํ•˜์˜€๋‹ค.

ScrollViewReader { proxy in
    ScrollView {
        Button(
            action: { withAnimation { proxy.scrollTo(bottomID) } },
            label: { Image(systemName: "chevron.down").foregroundColor(Color(.systemGray2)) })
            .id(topID)
        
        VStack(spacing: 16) {
            ForEach(0..50) { _ in
                Text("Scroll")
            }
        }
        .onChange(of: messageText == "") { _ in
            withAnimation { proxy.scrollTo(bottomID) }
        }
        
        HStack {}.id(bottomID)
    }
}

๊นƒํ—ˆ๋ธŒ ์ปค๋ฐ‹ ์ฃผ์†Œ

GitHub - Commit

์ข‹์€ ์›นํŽ˜์ด์ง€ ์ฆ๊ฒจ์ฐพ๊ธฐ