我是Swift的新手,我认为这是iOS编程的基本问题。
我的情节提要板上有三个按钮,我想自定义一次,两次和三次按下时这些按钮的外观。
我也有三个主题(粉红色,蓝色和橙色)。我想做的是创建三个新类,分别是粉红色,蓝色和橙色。
我不想以编程方式创建它们,而只是以编程方式对其进行样式设置。
我没有明白是怎么做的我调用函数(:例“ButtonIsPressed”从我)pink.swift类到我@IBAction和@IBOutlet在同样的主视图控制器面向对象(即我不想为每个按钮创建一个函数)?
我真的找不到合适的最新Swift 3教程,对此主题的任何帮助或建议将不胜感激。
为什么不能这么简单?:
@IBAction func buttonPressed(_ sender: UIButton!) {
self.backgroundColor = myPinkCGolor
}
我认为shallowThought的答案将适用于根据专门命名的IBOutlet的按钮状态更改backgroundColor。
我的情节提要板上有三个按钮,我想自定义一次,两次和三次按下时这些按钮的外观。
如果要保持“状态”,例如在“计数器”中单击或轻击按钮的次数,则可以使用按钮的“标记”属性。将其设置为零,并在IBAction函数中将其递增。(就像shallowThought所说的那样,对事件使用.touchUpInside和.touchDown。)
另外,您还有一个未成年人-但很重要!-您的代码Brewski中有错误:
@IBAction func buttonPressed(_ sender: UIButton!) {
self.backgroundColor = myPinkCGolor
}
应该:
@IBAction func buttonPressed(_ sender: UIButton!) {
sender.backgroundColor = myPinkCGolor
}
因此,将所有内容组合在一起-投票赞成shallowThought(也可以将他的AnyObject更改为UIButton,并在UIColors上使其成为Swift 3.x语法),并且最终会得出这样的结果。请注意,不需要IBOutlet,并且可以连接所有内容IB中无需子类化:
// .touchUpInside event
// can be adapted to show different color if you want, but is coded to always show white color
@IBAction func buttonClicked(sender: UIButton) {
sender.backgroundColor = UIColor.whiteColor()
}
// .touchDown event
// will show a different color based on tap counter
@IBAction func buttonReleased(sender: UIButton) {
switch sender.tag {
case 1:
sender.backgroundColor = UIColor.blue
case 2:
sender.backgroundColor = UIColor.red
case 3:
sender.backgroundColor = UIColor.green
default:
sender.backgroundColor = UIColor.yellow
}
sender.tag += 1
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句