【发布时间】:2016-08-12 08:33:30
【问题描述】:
我正在学习委托的概念,但我被困在我的项目中。我相信解决方案很简单,但由于这对我来说是新事物,所以我不知道出了什么问题。
项目概念很简单:
应用程序中有两个视图。在第一个视图中,您按下“更改颜色”按钮,结果出现第二个视图。在第二个视图中,有三个文本字段,用户分别在 RGB 颜色中输入 R G 和 B 值的数字。当点击按钮时,第二个视图消失,第一个视图的背景应该根据用户的输入改变颜色。我假设用户输入了正确的数字,因此此时我对这些值使用强制展开。
此时视图正确显示,但第一个视图的背景颜色没有改变,我不知道为什么。
下面是两个视图控制器的代码。我会很感激任何提示。
第一个 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)
}
}
【问题讨论】:
标签: ios swift uiviewcontroller delegates