RAJAMOHAN-S RAJAMOHAN-S - 1 month ago 13
Swift Question

How to execute custom delegate methods like UITableViewDataSource in swift?

I have a

UIButton
in one
UIViewController
. I am print the text by using custom delegate. Now, the problem is delegate method not execute at ideal when
viewDidAppear(animated)
.(i.e., like
UITableViewDataSource
)

Protocol:

protocol FruitDelegate{

func fruit(_ name:String,taste:String)->Bool
}


Fruit Class

class Fruit{

var delegate:FruitDelegate?

var name:String!
var taste:String!

init(name:String,taste:String){
self.name = name
self.taste = taste

}

func isTrue(){

if self.delegate?.fruit(name, taste: taste) == true{

print("Answer Correct")
}else{

print("Answer Wrong")
}
}

}


View Controller:

class ViewController: UIViewController,FruitDelegate {


@IBOutlet var textLabel: UILabel!

let fruit = Fruit(name: "mango", taste: "sweet")


override func viewDidLoad() {
super.viewDidLoad()

self.fruit.delegate = self
}

func fruit(_ name: String, taste: String) -> Bool {

if name == "mango" && taste == "sweet"{

return true
}else{
return false
}
}


@IBAction func actionRefreshButton(_ sender: UIButton) {

self.fruit.isTrue()
}


}


I know below code will give me the exact solution for my problem.

override func viewDidLoad() {
super.viewDidLoad()

self.fruit.delegate = self
self.fruit.isTrue()
}


But, Is it necessary to call
self.fruit.isTrue()
on
viewController
methods? (upto
viewDidAppear
). In
UITableView
there is no need to call
reloadData()
at ideal when view is appear. Same way, I need to execute
FruitDelegate
method. How to I do?

Answer Source

You only need to call isTrue method in your didSet of your delegate var

class Fruit{

    var delegate:FruitDelegate{
       didSet{
          self.isTrue()
       }
    }

    var name:String!
    var taste:String!

    init(name:String,taste:String){
        self.name = name
        self.taste = taste

    }

    func isTrue(){

        if self.delegate?.fruit(name, taste: taste) == true{

            print("Answer Correct")
        }else{

            print("Answer Wrong")
        }
    }

}