๊ธฐํƒ€/iOS๐ŸŽ

[iOS/Swift] Delegate Pattern, Closure๋ฅผ ์ด์šฉํ•ด ๋ฐ์ดํ„ฐ & ์ด๋ฒคํŠธ ์ „๋‹ฌํ•˜๊ธฐ

yujindonut 2022. 6. 13. 15:30
728x90

์ž‘๋™ ๋ฐฉ์‹ 

ํ™”๋ฉด1์—์„œ ์žฅ๋ฐ”๊ตฌ๋‹ˆํด๋ฆญ -> ํ™”๋ฉด2์—์„œ  ์ƒํ’ˆ์„ ํƒ -> ํ™”๋ฉด1์—์„œ ์ƒํ’ˆ์˜ ๊ฐœ์ˆ˜๋ฅผ ๋„์šฐ๋Š” alert์ฐฝ

 

 

 

 

- ๋ฐ์ดํ„ฐ ์š”์ฒญ์„ ๋ฐ›์€ Received View Controller์—์„œ Protocol ์ •์˜

protocol CartDelegate {
    func alarmCartIsFilled(itemCount: Int)
}

 

 

- ์นดํŠธ ๋ฒ„ํŠผ ํด๋ฆญํ–ˆ์„ ๋•Œ ๋‘๋ฒˆ์งธ์˜ ๋ทฐ์ปจํŠธ๋กค๋Ÿฌ์˜ ๊ถŒํ•œ์„ ์œ„์ž„ ์„ค์ •!

@IBAction func cartButtonTapped() {
	let cartVC = storyboard?.instantiateViewController(identifier: "ReceiveViewController") as! ReceiveViewController
    cartVC.delegate = self // cartVC์˜ ๊ถŒํ•œ์œ„์ž„ ๋ฐ›์Œ
        
    if let productName = productNameLabel.text,
    	let price = priceLabel.text {
        cartVC.productName = productName
        cartVC.price = price
    }
    present(cartVC, animated: true, completion: nil)
}

 

 

- ์žฅ๋ฐ”๊ตฌ๋‹ˆ ๋‹ด๊ธฐ ๋ฒ„ํŠผ์„ ํด๋ฆญํ–ˆ์„๋•Œ

    var delegate: CartDelegate?     // ๊ฐ์ฒด๊ฐ€ ๊ฐ€์ง€๋Š” ์–ด๋–ค ๊ถŒํ•œ // ํ”„๋กœํ† ์ฝœ์— ๋Œ€ํ•œ ๊ถŒํ•œ ์„ ์–ธ
    
    @IBAction func insertCartButtonTapped(_ sender: UIButton) {
        dismiss(animated: true, completion: nil)
        delegate?.alarmCartIsFilled(itemCount: itemCount) //์‹ ํ˜ธ๋ฅผ ์ „๋‹ฌ
    }

 

 

- ๋ฐ์ดํ„ฐ์š”์ฒญ์„ ๋ณด๋‚ธ SendViewController์—์„œ ํ”„๋กœํ† ์ฝœ์— ์ •์˜ํ•œ ํ•จ์ˆ˜๋ฅผ ์ •์˜ํ•œ๋‹ค.

( alert์ฐฝ์„ ๋„์–ด์คŒ )

    func alarmCartIsFilled(itemCount: Int) { // ์‹ ํ˜ธ๋ฅผ ๋ฐ›๊ณ  ์‹คํ–‰๋จ
        let alertVC = UIAlertController(title: "์žฅ๋ฐ”๊ตฌ๋‹ˆ ํ™•์ธ", message: "์žฅ๋ฐ”๊ตฌ๋‹ˆ์— \(itemCount)๊ฐœ์˜ ์ƒํ’ˆ์ด ์ถ”๊ฐ€๋˜์—ˆ์Šต๋‹ˆ๋‹ค.", preferredStyle: .alert)

        let okAction = UIAlertAction(title: "ํ™•์ธ", style: .default, handler: nil)
        alertVC.addAction(okAction)

        present(alertVC, animated: true, completion: nil)
    }

 

 


์ถœ์ฒ˜

SOPT 7์ฃผ์ฐจ ์„ธ๋ฏธ๋‚˜

728x90