简体   繁体   中英

UIButton Function add Tap Style

I Have written a function in Swift 4 which creates a button that receives the UIButton , a Color and a String for the title. I would like to add to this function a highlight or tap style but I am not sure how.

The function:

 func homeBtn(button: UIButton, color: UIColor, title: String){
    button.setTitle(title, for: .normal)
    button.setTitleColor(color, for: .normal)
    button.titleLabel?.font =  UIFont(name: "Raleway-Medium", size: 24)
    button.titleLabel?.lineBreakMode = .byWordWrapping
    button.titleLabel?.textAlignment = .center
    button.titleEdgeInsets = UIEdgeInsetsMake(20,20,20,20)
    button.layer.borderColor = color.cgColor
    button.layer.borderWidth = 2
    button.layer.cornerRadius = button.frame.width/2
    button.layer.backgroundColor = whiteColor.cgColor
 }

The button is a circle and has a String centered in the middle with the UIColor being used as an outline. Can someone show me how to add a tap style to this function that uses the same UIColor to fill in the button and turn the text white please?

For the title color you can easily do this without adding events.

button.setTitleColor(.white, for: .highlighted)
button.setTitleColor(.black, for: .normal)

For the background color you need to define the following events:

    button.addTarget(self, action: #selector(touchDown(button:)), for: .touchDown)
    button.addTarget(self, action: #selector(touchUpInside(button:)), for: .touchUpInside)

Define functions - You can refer additional touch types as well - see UIControlEvents

@objc func touchDown(button: UIButton) {
    guard let borderColor = button.layer.borderColor else {
        return
    }
    button.backgroundColor = UIColor(cgColor: borderColor)
}

@objc func touchUpInside(button: UIButton) {
    // Set backgroundColor for normal state...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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