斯威夫特委托不工作
Posted
技术标签:
【中文标题】斯威夫特委托不工作【英文标题】:Swift delegate not working 【发布时间】:2016-02-12 02:38:48 【问题描述】:我的 ViewController 中有一个步进器,用于控制 UIView 中变量的值。当我在 UIView 中将变量重置为 0 时,我还希望重置步进器和标签,但它们不会。我尝试使用委托,但出现错误。提前致谢!
视图控制器:
protocol CircleViewDelegate: class
func updateStepper(view: CircleView)
class ViewController: UIViewController, CircleViewDelegate
var colors = CircleView()
@IBOutlet weak var circleView1: CircleView!
@IBOutlet weak var blueStepper: UIStepper!
@IBOutlet weak var greenStepper: UIStepper!
@IBOutlet weak var redStepper: UIStepper!
@IBOutlet weak var redValue: UILabel!
@IBOutlet weak var greenValue: UILabel!
@IBOutlet weak var blueValue: UILabel!
var circleViewDelegate: CircleView!
override func viewDidLoad()
super.viewDidLoad()
circleViewDelegate!.delegate = self
func updateStepper(view: CircleView)
redStepper.value=0.0;
greenStepper.value=0.0;
blueStepper.value=0.0;
@IBAction func stepperChange(sender: UIStepper)
circleView1.redd1 = Int(redStepper.value);
redValue.text = Int(sender.value).description;
@IBAction func stepperChange1(sender: UIStepper)
circleView1.greenn1 = Int(greenStepper.value);
greenValue.text = Int(sender.value).description;
@IBAction func stepperChange2(sender: UIStepper)
circleView1.bluee1 = Int(blueStepper.value);
blueValue.text = Int(sender.value).description;
UIView:
class CircleView: UIView
var redd1 = 0
var greenn1 = 0
var bluee1 = 0
weak var delegate: CircleViewDelegate?
func updateStepper()
delegate?.updateStepper(self)
func game()
if(redd1==Int(red1) && greenn1==Int(green1) && bluee1==Int(blue1))
redd1 = 0;
green1 = 0;
blue1 = 0;
updateStepper()
【问题讨论】:
你得到的错误是什么? 在这一行: circleViewDelegate!.delegate = self ,我得到错误:EXC_BAD_INSTRUCTION 你不需要circleViewDelegate
- 你想说circleView1.delegate=self
谢谢我修好了,但我的问题仍然存在
设置断点。你的委托方法被调用了吗?
【参考方案1】:
试试这个:
override func viewDidLoad()
super.viewDidLoad()
circleView1.delegate = self
func updateStepper(view: CircleView)
redStepper.value = 0.0
greenStepper.value = 0.0
blueStepper.value = 0.0
stepperChange(redStepper)
stepperChange(greenStepper)
stepperChange(blueStepper)
【讨论】:
我已经更新了调用IBAction
方法的答案,您可能希望调用该方法。这将更新标签和CircleView
。【参考方案2】:
不要在viewDidLoad
中分配像这样circleViewDelegate!.delegate = self
的委托,而是尝试circleView1.delegate = self
【讨论】:
它修复了错误,但我的问题仍然存在同样的问题以上是关于斯威夫特委托不工作的主要内容,如果未能解决你的问题,请参考以下文章
添加了 UITableViewCell GestureRecognizer 委托不工作