๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๐Ÿ“ฑ Mobile/iOS

[iOS - UIKit] ScrollView์—์„œ Button ํด๋ฆญ ์‹œ ํ™”๋ฉด์˜ ์ตœ์ƒ๋‹จ, ์ตœํ•˜๋‹จ ์ด๋™

์˜ค๋Š˜์€ ScrollView๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ์— ํŽ˜์ด์ง€์˜ ๋‚ด์šฉ์ด ๋งŽ์•„ ์Šคํฌ๋กค์ด ๊ธธ์–ด์ง€๊ฒŒ ๋˜๋ฉด ์–ดํ”Œ ์•ˆ์˜ ๋ฒ„ํŠผ์„ ํ„ฐ์น˜ํ•จ์œผ๋กœ์จ ์ตœ์ƒ๋‹จ ๋˜๋Š” ์ตœํ•˜๋‹จ์œผ๋กœ ๊ฐ€๋Š” ๊ตฌํ˜„ ๋ฐฉ๋ฒ•์„ ์•Œ์•„๋ณด๋ ค๊ณ  ํ•œ๋‹ค. 

 

 

๊ตฌํ˜„ ๋ฐฉ๋ฒ•

  1. ViewController์—์„œ UIScrollViewDelegate ์ฑ„ํƒ
  2. ScrollView๋ฅผ ์Šคํฌ๋กคํ•˜๊ฒŒ ๋˜๋ฉด x, y์ถ•์ด ๋ณ€ํ•˜๊ฒŒ ๋œ๋‹ค.
  3. button์„ ํด๋ฆญํ–ˆ์„๋•Œ event๋ฅผ x, y์ถ•์ด (0, 0)์ด ๋˜๋„๋ก ํ•œ๋‹ค.

์ฝ”๋“œ

class ViewController: UIViewController,UIScrollViewDelegate {
    // code 
}

 

 

๋ฐฉ๋ฒ• 1 - ์ตœ์ƒ๋‹จ ์ด๋™

@objc func scrollToTop(_ sender: UIButton) {    
	collectionView.scrollToItem(at: IndexPath(row: 0, section: 0), 
	at: .top, animated: true)
}

 

 

๋ฐฉ๋ฒ• 2 - ์ตœ์ƒ๋‹จ ์ด๋™

collectionView.setContentOffset(CGPoint(x: 0, y: 0), animated: true)

 

 

๋ฐฉ๋ฒ• 3 - ์ตœํ•˜๋‹จ ์ด๋™

collectionView.setContentOffset(CGPoint(x: 0, y: collectionView.contentSize.height - collectionView.bounds.height), animated: true)

 

 

→ ์ขŒํ‘œ๋ฅผ ์ˆ˜์ •ํ•ด์„œ ์›ํ•˜๋Š” ์œ„์น˜๋กœ ์ด๋™ํ•  ์ˆ˜ ์žˆ๋‹ค! 

 

 

 

728x90