I am trying to work with delegate and protocol but met a problem.
I created 2 buttons on one ViewController and created 1 imageView in another ShowViewController. The color of the imageView will change according to which button is pressed.
ViewController.swift
import UIKit
protocol getColorProtocol {
func getColor(color:String?)
}
class ViewController: UIViewController {
var color: String?
var delegate:getColorProtocol?
@IBAction func blueButtonPressed(_ sender: Any) {
color = "blue"
delegate?.getColor(color: color)
}
@IBAction func redButtonPressed(_ sender: Any) {
color = "red"
delegate?.getColor(color: color)
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
ShowViewController.swift
import UIKit
class ShowViewController: UIViewController, getColorProtocol {
var viewOne = ViewController()
@IBOutlet weak var colorView: UIImageView!
func getColor(color: String?) {
print("color is \(color!)")
if color == "red"{
colorView.backgroundColor = UIColor(displayP3Red: 255/255, green: 0/255, blue: 0/255, alpha: 1)
}
else if color == "blue" {
colorView.backgroundColor = UIColor(displayP3Red: 0/255, green: 0/255, blue: 255/255, alpha: 1)
}
}
override func viewDidLoad() {
super.viewDidLoad()
viewOne.delegate = self
}
}
press here to view the storyboard!
You may check my storyboard above.
Currently, it has no error but it cannot call the getColor function. I am wondering if the problem is coming from the delegate?.getColor(color: color)
statement.
Any ideas?
First of all, in your case, you don't need to use delegate pattern
Your ViewController
connect directly to ShowViewController
through segue
You can use prepareForSegue
instead
Secondly, I don't think you understand how delegate pattern
works, Inside ShowViewController, you're create a new ViewController
called viewOne
, it isn't the original ViewController
so that's why your code doesn't work as expected
As I mentioned above, you should use segue
first, go to the storyboard
setup your segue identifier. Then, inside your ViewController
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if (segue.identifier == "goToShowVC") {
//your code here
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments