我被这篇作业难住了。也许有人能告诉我怎么解决这个问题。
"VC包含一个带有内置控制器的控制器。父控制器和子控制器都有三个按钮:绿色,黄色,紫色。当您单击父控制器中的一个按钮时,子控制器的背景颜色将更改为适当的颜色。当你点击子元素中的按钮时,父元素的背景会改变。">
这是我在代码中所做的
父VC
import UIKit
class OrangeViewController: UIViewController, VioletControllerDelegate {
var delegate: VioletControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vcV = segue.destination as! VioletViewController
vcV.bgColor = view.backgroundColor
vcV.delegate = self
}
@IBAction func greenOButton(_ sender: Any) {
//TO DO
}
@IBAction func yellowOButton(_ sender: Any) {
//TO DO
}
@IBAction func purpleOButton(_ sender: Any) {
//TO DO
}
func setColor(color: String) {
view.backgroundColor = UIColor(named: color)
}
}
孩子VC
import UIKit
protocol VioletControllerDelegate{
func setColor ( color : String)
}
class VioletViewController: UIViewController {
var bgColor : UIColor?
var delegate: VioletControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
var bgColor = view.backgroundColor
}
@IBAction func setGreen(_ sender: Any) {
delegate?.setColor( color: "green")
}
@IBAction func setYellow(_ sender: Any) {
delegate?.setColor( color: "yellow")
}
@IBAction func setViolet(_ sender: Any) {
delegate?.setColor( color: "violet")
}
func setColor ( color : String){
view.backgroundColor = UIColor(named: color)
}
}
谢谢!
我做到了。如果有人需要这样的东西,我张贴我的答案:
父VC
import UIKit
class OrangeViewController: UIViewController, VioletControllerDelegate {
var childVC: VioletViewController?
override func viewDidLoad() {
super.viewDidLoad()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vcV = segue.destination as! VioletViewController
self.childVC = vcV
vcV.delegate = self
}
@IBAction func greenOButton(_ sender: Any) {
childVC?.view.backgroundColor = UIColor.green
}
@IBAction func yellowOButton(_ sender: Any) {
childVC?.view.backgroundColor = UIColor.yellow
}
@IBAction func purpleOButton(_ sender: Any) {
childVC?.view.backgroundColor = UIColor.purple
}
func setColor( color : UIColor) {
view.backgroundColor = color
}
}
孩子VC
import UIKit
protocol VioletControllerDelegate{
func setColor ( color : UIColor)
}
class VioletViewController: UIViewController {
var delegate: VioletControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func setGreen(_ sender: Any) {
delegate?.setColor( color: UIColor.green)
}
@IBAction func setYellow(_ sender: Any) {
delegate?.setColor( color: UIColor.yellow)
}
@IBAction func setViolet(_ sender: Any) {
delegate?.setColor( color: UIColor.purple)
}
}