我正在学习授权的概念,我被困在我的项目中。我相信解决方案很简单,但是这对我来说是新的,我不知道出了什么问题。
项目概念很简单:
应用程序中有两个视图。在第一个视图中,按下按钮"更改颜色"结果出现第二个视图。在第二个视图中,有三个文本字段,其中用户分别为RGB颜色的R G和B值放置数字。当点击按钮时,第二视图消失,并且应该根据用户的输入用颜色改变第一视图的背景。我假设用户输入正确的数字,因此此时我使用强制解包这些值
此时视图显示正确,但第一个视图的背景颜色不会改变,我不知道为什么。
Beneath是两个视图控制器的代码。我会很感激任何提示。
第一个VC:ViewController.swift
class ViewController: UIViewController, ColorChangeDelegate {
let secondStoryboard = UIStoryboard(name: "Second", bundle: nil).instantiateViewControllerWithIdentifier("SecondViewController") as UIViewController
var secondVC = SecondViewController()
@IBAction func changeColourButtonTapped(sender: UIButton) {
presentViewController(secondStoryboard, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
secondVC.colorDelegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func didChangeColor(controller: SecondViewController, color: UIColor) {
self.view.backgroundColor = color
}
}
和第二个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()
// Do any additional setup after loading the view.
myRTextField.delegate = self
myGTextField.delegate = self
myBTextField.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be 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)
}
}
答案 0 :(得分:0)
您要将代理人分配给secondVC
,但实际呈现的视图控制器位于secondStoryboard
,因此您应设置colorDelegate
的{{1}}属性。< / p>