我有“屏幕 A”和“屏幕 B”,我在“屏幕 A”上有按钮,使用它我可以导航到“屏幕 B”,
在“屏幕 B”上,我有两个按钮“红色按钮”和“绿色按钮”,我想通过按下“屏幕 B”上的按钮来更改“屏幕 A”的颜色
我想用委托(delegate)来做到这一点
即使是 Objective-C 中的解决方案也很有帮助
最佳答案
您可以通过以下方式进行:
protocol ViewControllerBDelegate: class {
func changeColor(color : UIColor)
}
class ViewControllerB: UIViewController {
weak var delegate : ViewControllerBDelegate?
@IBAction func changeColorInViewController(sender: UIButton) {
// send the message to change the color in A regarding the color
sender.tag == 0 ? delegate?.changeColor(UIColor.redColor()) :
delegate?.changeColor(UIColor.greenColor())
}
}
上面的 ViewController
是 ViewControllerB
,您要在其中更改 ViewControllerA
的颜色。
然后你可以用下面的方式实现ViewControllerA
:
class ViewControllerA: UIViewController , ViewControllerBDelegate {
var viewControllerB : ViewControllerB!
// In this method you receive the notification when the button in B is tapped
func changeColor(color: UIColor) {
self.view.backgroundColor = color
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var dest = segue.destinationViewController as! ViewControllerB
self.viewControllerB = dest // instantiate the reference
self.viewControllerB.delegate = self // set the delegate for B
}
}
两件重要的事情:
- 我在
prepareForSegue
中设置了对ViewControllerB
的引用,因为你有一个按钮可以打开ViewControllerB
,但是你手动显示它你可以随心所欲地改变它。 - 我只为
ViewControllerB
中的两个按钮实现了一个action
,并为每个按钮分配了一个tag
(您可以在Interface Builder 或代码中)来识别它并发送与按下的按钮相关的颜色,但如果需要,您可以单独执行。
希望对你有帮助
关于ios - 我怎样才能 swift 改变一个屏幕从另一个屏幕的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29414727/