ios - Delegation between two ViewControllers without segues -
i learning concept of delegation , stuck in project. believe solution simple, new me have no idea wrong.
project concept simple:
there 2 views in application. in first view press button "change color" , result second view appears. in second view there 3 text fields user puts numbers respectively r g , b values in rgb color. when button tapped, second view disappears , first view's background should changed color based on user's input. assume user put correct numbers, therefore @ moment use forced unwrapping values.
@ moment views appear correctly, background color of first view not change , have no idea why.
beneath code 2 view controllers. appreciate hints.
first vc: viewcontroller.swift
class viewcontroller: uiviewcontroller, colorchangedelegate { let secondstoryboard = uistoryboard(name: "second", bundle: nil).instantiateviewcontrollerwithidentifier("secondviewcontroller") uiviewcontroller var secondvc = secondviewcontroller() @ibaction func changecolourbuttontapped(sender: uibutton) { presentviewcontroller(secondstoryboard, animated: true, completion: nil) } override func viewdidload() { super.viewdidload() // additional setup after loading view, typically nib. secondvc.colordelegate = self } override func didreceivememorywarning() { super.didreceivememorywarning() // dispose of resources can recreated. } func didchangecolor(controller: secondviewcontroller, color: uicolor) { self.view.backgroundcolor = color }
}
and second vc: secondviewcontroller.swift
protocol colorchangedelegate { func didchangecolor(controller: secondviewcontroller, color: uicolor) } class secondviewcontroller: uiviewcontroller, uitextfielddelegate { @iboutlet weak var myrtextfield: uitextfield! @iboutlet weak var mygtextfield: uitextfield! @iboutlet weak var mybtextfield: uitextfield! var colordelegate : colorchangedelegate? override func viewdidload() { super.viewdidload() // additional setup after loading view. myrtextfield.delegate = self mygtextfield.delegate = self mybtextfield.delegate = self } override func didreceivememorywarning() { super.didreceivememorywarning() // dispose of resources can recreated. } func textfielddidbeginediting(textfield: uitextfield) { textfield.becomefirstresponder() } @ibaction func gobuttontapped(sender: uibutton) { let r = int(myrtextfield.text!)! let g = int(mygtextfield.text!)! let b = int(mybtextfield.text!)! let color = uicolor(red: cgfloat(r), green: cgfloat(g), blue: cgfloat(b), alpha: 1.0) self.view.endediting(true) colordelegate?.didchangecolor(self, color: color) presentingviewcontroller?.dismissviewcontrolleranimated(true, completion: nil) } }
you assigning delegate secondvc
view controller being presented in secondstoryboard
, should set colordelegate
property of secondstoryboard
.
Comments
Post a Comment