Delegate Pattern

Delegate Pattern

Sources from

Protocol

Example

protocol Runable {
	var regCount:Int {get set} // regCount 프로퍼티를 무조건 만들어야 하며, getter, setter를 모두 구현해야 한다.
 	func run()
}

Delegate


Sample code 01. UITableView

UITableViewDelegate 프로토콜 선언

public protocol UITableViewDelegate : NSObjectProtocol, UIScrollViewDelegate {

    // Display customization
    
    @available(iOS 2.0, *)
    optional public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath)

    @available(iOS 6.0, *)
    optional public func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int)

    @available(iOS 6.0, *)
    optional public func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int)

    @available(iOS 6.0, *)
    optional public func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath)

...

UITableView 클래스에 delegate 프로퍼티 생성

open class UITableView : UIScrollView, NSCoding, UIDataSourceTranslating {

    
    public init(frame: CGRect, style: UITableViewStyle) // must specify style at creation. -initWithFrame: calls this with UITableViewStylePlain

    public init?(coder aDecoder: NSCoder)

    
    open var style: UITableViewStyle { get }

    
    weak open var dataSource: UITableViewDataSource?

    weak open var delegate: UITableViewDelegate?
    
    
    ...
    

구현부

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        let tableView: UITableView = UITableView(frame: view.bounds, style: .plain)
        tableView.dataSource = self // UITableViewDataSource 선언
        tableView.delegate = self // UITableViewDelegate 선언
        
        // class 로서 tableView에 등록
        tableView.register(Cell.self, forCellReuseIdentifier: "Cell")
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        // UITableViewCell.self : class이름.self = 클래스 자체
        // dequeueReusableCell 얘가 UI를 만들 수 있도록 등록하는 과정
        view.addSubview(tableView)
    }
    

Sample code 02. Custom View

CustomViewDelegate 프로토콜 생성

protocol CustomViewDelegate {
    func didSwitchedCustomView(_ customView: CustomView)
    func didDeSwitchedCustomView(_ customView: CustomView)
}

UIView인 CustomView 클래스에 delegate 정의

import UIKit
class CustomView: UIView {
    
    var delegate: CustomViewDelegate?
    
    @IBOutlet var titleLabel: UILabel!
    @IBOutlet var imageView: UIImageView!
    @IBOutlet var switchBtn: UISwitch!
    
    @IBAction func switching(_ sender: UISwitch) {
        if sender.isOn {
            delegate?.didSwitchedCustomView(self)
        }else {
            delegate?.didDeSwitchedCustomView(self)
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        switchBtn.isOn = false
        imageView.contentMode = UIViewContentMode.center
    }
    
}

ViewController에서 실제 메소드 구현

import UIKit

class ViewController: UIViewController, CustomViewDelegate {
    
    @IBOutlet var newCustomView: CustomView!
    var starimage: UIImage?
    
    func didSwitchedCustomView(_ customView: CustomView) {
        customView.titleLabel.text = "샌프란시스코로 떠나시겠습니까?"
        customView.imageView.image = nil
    }
    
    func didDeSwitchedCustomView(_ customView: CustomView) {
        customView.titleLabel.text = "Welcome to AirBnb"
        customView.imageView.image = UIImage(named: "Logo")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        newCustomView.delegate = self
        starimage = UIImage(named: "staricon")
    }
    
}