๐Ÿ‘ฏโ€โ™€๏ธDelegate ํŒจํ„ด ์‚ฌ์šฉํ•˜๊ธฐ

sangheeยท2021๋…„ 12์›” 13์ผ
2

๐ŸšฉiOS

๋ชฉ๋ก ๋ณด๊ธฐ
18/18
post-custom-banner

๊ฐ์ฒด ๊ฐ„์˜ ํ†ต์‹  ์„ธ๊ฐ€์ง€ ์ข…๋ฅ˜

๊ฐ์ฒด ๊ฐ„์— ๋ฐ์ดํ„ฐ๋ฅผ ์ฃผ๊ณ ๋ฐ›๋Š” ๋ฐฉ๋ฒ•์€ ์„ธ๊ฐ€์ง€๊ฐ€ ์žˆ๋‹ค.

  1. Delegate: ํŠน์ • ๊ฐ์ฒด์—์„œ ๋ฐœ์ƒํ•œ ์ด๋ฒคํŠธ๋ฅผ ๋‹ค๋ฅธ ๊ฐ์ฒด์—๊ฒŒ ํ†ต๋ณดํ•  ์ˆ˜ ์žˆ๋‹ค.
  2. Notification: ์ด๋ฒคํŠธ์— ๋Œ€ํ•ด ์—ฌ๋Ÿฌ ๋ฆฌ์Šคํ„ฐ๊ฐ€ ์žˆ์„ ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค. ์žฌ์‚ฌ์šฉํ•˜๋Š” ๊ฒฝ์šฐ์—๋Š” ํด๋ž˜์Šค ๊ธฐ๋ฐ˜์˜ delegate ํŒจํ„ด์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์ข‹๋‹ค.
  3. Block: ์ด๋ฒคํŠธ๊ฐ€ ๋”ฑ ํ•˜๋‚˜์ผ ๋Œ€ ์‚ฌ์šฉํ•œ๋‹ค. Completion block์„ ์‚ฌ์šฉํ•˜๋Š” ์˜ˆ์ด๋‹ค.

์ด์ค‘์—์„œ ์šฐ๋ฆฌ๋Š” Delegate ํŒจํ„ด์— ๋Œ€ํ•ด ์‚ดํŽด๋ณธ๋‹ค.

Delegate ํŒจํ„ด์ด๋ž€?

delegate๋ผ๋Š” ๋‹จ์–ด๋Š” ์œ„์ž„ํ•˜๋‹ค๋ผ๋Š” ๋œป์„ ๊ฐ€์ง€๊ณ  ์žˆ๋‹ค. ์ฆ‰, Delegate ํŒจํ„ด์ด๋ž€ ๊ฐ์ฒด๊ฐ€ ๋‹ค๋ฅธ ๊ฐ์ฒด์—๊ฒŒ ์ž์‹ ์˜ ์ผ์„ ์œ„์ž„ํ•˜๋Š” ๊ฒƒ์ด๋‹ค.

์‹ค์ œ ์˜ˆ์‹œ

์ง€๊ธˆ ํ•˜๋Š” ํ”„๋กœ์ ํŠธ๋ฅผ ๊ฐ€์ ธ์™”๋‹ค. ์™ผ์ชฝ์˜ ๋ทฐ์ปจํŠธ๋กค๋Ÿฌ์ด๊ณ , ์˜ค๋ฅธ์ชฝ์€ ๋ทฐ์ปจํŠธ๋กค๋Ÿฌ ์•ˆ์˜ ์…€์ด๋‹ค. ์…€์˜ ์ปค๋ฒ„๋ณ€๊ฒฝ ๋ฒ„ํŠผ์„ ํด๋ฆญํ•˜์˜€์„ ๋•Œ, ๋ทฐ์ปจํŠธ๋กค๋Ÿฌ์—์„œ ์ƒˆ๋กœ์šด ๋ทฐ ์ปจํŠธ๋กค๋Ÿฌ๋ฅผ ๋„์šฐ๋ ค๊ณ  ํ•œ๋‹ค.

์…€์˜ ์ปค๋ฒ„๋ณ€๊ฒฝ ๋ฒ„ํŠผ์„ ํด๋ฆญํ•˜์˜€์„ ๋•Œ ์ฒ˜๋ฆฌํ•  ์ฝ”๋“œ๋“ค์„ ๋ทฐ์ปจํŠธ๋กค๋Ÿฌ์— ์œ„์ž„ํ•˜๋ ค๊ณ  ํ•œ๋‹ค.

์…€

์…€์—์„œ ํ•ด์•ผ ํ•  ์ผ์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

1๏ธโƒฃ. ํ”„๋กœํ† ์ฝœ ๋งŒ๋“ค๊ณ  ์•ˆ์— ๋ฉ”์„œ๋“œ(changeCoverImage) ์ถ”๊ฐ€ํ•œ๋‹ค.
2๏ธโƒฃ. delegate๋ฅผ ์•ฝํ•œ ์ฐธ์กฐ๋กœ ์ฐธ์กฐํ•œ๋‹ค.
3๏ธโƒฃ. ์ปค๋ฒ„ ๋ณ€๊ฒฝ ๋ฒ„ํŠผ(imageChangeButton)์ด ํด๋ฆญ๋˜์—ˆ์„ ์‹œ delegate์˜ ๋ฉ”์„œ๋“œ๋ฅผ ์‹คํ–‰ํ•œ๋‹ค.

1๏ธโƒฃprotocol HomeWritingImageCellDelegate: AnyObject {
    func changeCoverImage()
}

final class HomeWritingImageCell: UICollectionViewCell {

    2๏ธโƒฃweak var delegate: HomeWritingImageCellDelegate?
    
    override func awakeFromNib() {
        super.awakeFromNib()
        configureButton()
    }
}

private extension HomeWritingImageCell {
    func configureButton() {
        3๏ธโƒฃimageChangeButton.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
        
        @objc func buttonTapped() {
            3๏ธโƒฃdelegate?.changeCoverImage()
        }
    }
}

๋ทฐ์ปจํŠธ๋กค๋Ÿฌ

๋ทฐ์ปจํŠธ๋กค๋Ÿฌ์—์„œ ํ•ด์•ผ ํ•  ์ผ์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

1๏ธโƒฃ. cell์˜ delegate๋ฅผ ์ž๊ธฐ ์ž์‹ (๋ทฐ์ปจํŠธ๋กค๋Ÿฌ)์œผ๋กœ ์„ค์ •ํ•œ๋‹ค.
2๏ธโƒฃ. ํ”„๋กœํ† ์ฝœ์„ ์ค€์ˆ˜ํ•œ๋‹ค.

final class HomeWritingViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        1๏ธโƒฃcell.delegate = self
    }

2๏ธโƒฃextension HomeWritingViewController: HomeWritingImageCellDelegate {
    func changeCoverImage() {
        // ์ปค๋ฒ„ ๋ณ€๊ฒฝ ๋ฒ„ํŠผ ํด๋ฆญ์‹œ ์‹คํ–‰ํ•  ์ฝ”๋“œ ์ž‘์„ฑ
    }
}
profile
๐Ÿ‘ฉโ€๐Ÿ’ป
post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€