在Swift3中使用一个类定制一个按钮和它的高亮状态



我是Swift新手,我认为这是iOS编程的一个基本问题。

我的故事板中有三个按钮,我想定制这些按钮在按一次,两次和三次时的外观。

我也有三个主题(粉红色,蓝色和橙色)。我想做的是创建三个新类,分别是pink,blue和orange。swift

我不想以编程的方式创建它们,只想以编程的方式为它们设置样式。

我缺乏理解的是我如何从我的pink.swift类调用函数(示例:"ButtonIsPressed")到我的@IBAction和@IBOutlet在主视图控制器,也是面向对象的(即:我不想为每个按钮创建一个函数)?

我真的找不到一个像样的和最新的Swift 3教程,任何关于这个主题的帮助或建议将非常感激。

为什么不能像……那么简单?:

@IBAction func buttonPressed(_ sender: UIButton!) {
    self.backgroundColor = myPinkCGolor
}

我认为shallowThought的答案将适用于根据特定命名的IBOutlet的按钮状态更改backgroundColor。

我的故事板中有三个按钮,我想定制这些按钮在按一次,两次和三次时的外观。

如果你想保持"状态",比如有一个按钮被点击或点击的次数的"计数器",你可以使用按钮的"tag"属性。将其设置为0,并在IBAction函数中增加它。(就像shallowThought说的,使用。touchupinside和。touchdown作为事件)

同样,你有一个次要的——但重要的!你的代码有问题吗?

@IBAction func buttonPressed(_ sender: UIButton!) {
    self.backgroundColor = myPinkCGolor
}
应:

@IBAction func buttonPressed(_ sender: UIButton!) {
    sender.backgroundColor = myPinkCGolor
}

所以把所有的东西结合起来投票给shallowThought(同时,把他的AnyObject改为UIButton,并使它成为Swift 3)。在UIColors上使用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
}

没有办法为特定状态设置backgroundColor,就像其他UIButton属性一样,所以你必须听按钮的动作:

class ViewController: UIViewController {
    @IBOutlet weak var button: UIButton!
    @IBAction func buttonClicked(sender: AnyObject) { //Touch Up Inside action
        button.backgroundColor = UIColor.whiteColor()
    }
    @IBAction func buttonReleased(sender: AnyObject) { //Touch Down action
        button.backgroundColor = UIColor.blueColor()
    }
    ...
}

或用image:UIImage, forState:.selected设置单色图像

最新更新