简体   繁体   English

快速按下时突出显示按钮

[英]Highlight a button when Pressed In swift

I Have Already made the Outlets and the action.我已经做了奥特莱斯和行动。 I have linked the code to the UI.我已将代码链接到 UI。

I want a button to be highlighted when pressed.我想要一个按钮在按下时突出显示。 This the code I wrote:这是我写的代码:

 @IBAction func buttonPressed(_ sender: UIButton) {
        sender.setTitleColor(UIColor(GL_GREEN), for: .highlighted)
}

You can subclass a UIButton. 您可以子类化UIButton。 Create a new swift file and name it anything you want but in this example I will name it HighlightedButton. 创建一个新的swift文件,并将其命名为您想要的任何内容,但在本例中,我将其命名为HighlightedButton。 Add below code in the new file you created. 在您创建的新文件中添加以下代码。 The class is named same as the file you created. 该类的名称与您创建的文件相同。

import UIKit

class HighlightedButton: UIButton {

    override var isHighlighted: Bool {
        didSet {
            backgroundColor = isHighlighted ? .red : .green
        }
    }
}

Next step is to set HighlightedButton as the class of your button: 下一步是将HighlightedButton设置为按钮的类:

In storyboard choose the UIButton you want to change. 在故事板中选择您要更改的UIButton。 In the identity inspector in the right corner there is a filed named "class" there type "HighlightedButton" and press enter. 在右上角的身份检查器中,有一个名为“class”的字段,其中键入“HighlightedButton”并按Enter键。 Now your button will change color to red when it is highlighted and back to green when you release the button. 现在,当您突出显示按钮时,按钮会将颜色更改为红色,然后返回绿色。

You can change to any color you want. 您可以更改为您想要的任何颜色。

You have to make 2 actions one is "Touch down" and "Touch up inside" action . 你必须做出两个动作,一个是“向下触摸”和“向内触摸”动作。 change background color for both of the action and you will achieve your target 更改两个动作的背景颜色,您将实现目标

In 2021... 2021年...

You just need to set the ButtonType to be .system and it will highlight when pressed.您只需将 ButtonType 设置为 .system ,按下时它会突出显示。

let button = UIButton(type: .system)

Here's a button I made, for clarity:为了清楚起见,这是我制作的一个按钮:

lazy var myButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Show More", for: .normal)
        button.setTitleColor(.systemBlue, for: .normal)
        button.titleLabel?.font = .systemFont(ofSize: 17, weight: .regular)
        button.layer.masksToBounds = true
        button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
        return button
}()
    
@objc fileprivate func buttonTapped() {
        //code for segue
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM