How to delegate from separate class other than ViewController class

`import UIKit`

`class Names`

`{`

`static let names = ["T","A","H","A"]`

`}`

`class ViewController: UIViewController`

`{`

`override func viewDidLoad()`

`{`

`super.viewDidLoad()`

`showView()`

`}`

`func showView()`

`{`

`let picker = UIPickerView()`

`picker.delegate = self`

`picker.dataSource = self`

`view.addSubview(picker)`

`}`

`}`

`extension ViewController: UIPickerViewDelegate, UIPickerViewDataSource`

`{`

`func numberOfComponents(in pickerView: UIPickerView) -> Int {`

`return 1`

`}`

`func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {`

`Names.names.count`

`}`

`func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {`

`let localrow = Names.names[row]`

`return localrow`

`}`

`}`

this class just show a picker with four letters, however all the code is inside the main View i.e ViewController. what I want is how to create a separate class that will contain the datasource the delegate, and the UIPickerView for the UIPicker. and just use that class in main viewdidload. for example

`class ViewController: UIViewController`

`{`

`override func viewDidLoad()`

`{`

`super.viewDidLoad()`

`let picker = MyPickerClass`

`view.addsubview(picker)`

`}`
class PickerDelegate: UIPickerViewDelegate, UIPickerViewDataSource {
// etc.
}

func showView() {
  pickerDelegate = PickerDelegate()
  let picker = UIPickerView()
  picker.delegate = pickerDelegate
  picker.dataSource = pickerDelegate
  view.addSubview(picker)
}

Cannot declare conformance to 'NSObjectProtocol' in Swift; 'PickerDelegate' should inherit 'NSObject' instead

Glad you figured it out.

Yes, the delegate callbacks need to be on an NSObject subclass.

This design can be called MVVM where your delegate object is a View Model. If you have multiple pickers or similar in a single view controller this is a good way to implement separation of concerns.

Terms of Service

Privacy Policy

Cookie Policy