Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make UIView change color when pressed?

Tags:

ios

swift

uiview

I would like to make a UIView highlighted after it's pressed and return to the normal color after release. What is the best practise for doing this?

like image 568
ErikLm Avatar asked Dec 11 '22 08:12

ErikLm


2 Answers

Subclass the UIView:

class CustomView: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.blue
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        backgroundColor = UIColor.red
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesEnded(touches, with: event)
        backgroundColor = UIColor.blue
    }
}

Apple about overriding touchesBegan and touchesEnded:

When creating your own subclasses, call super to forward any events that you do not handle yourself. If you override this method without calling super (a common use pattern), you must also override the other methods for handling touch events [i.e. touchesEnded, touchesMoved, touchesCancelled], even if your implementations do nothing.

Further reading:

https://developer.apple.com/documentation/uikit/uiview

Proper practice for subclassing UIView?

like image 172
liquid LFG UKRAINE Avatar answered Dec 27 '22 05:12

liquid LFG UKRAINE


Very simple example - you can run it in a Playground page:

//: Playground - noun: a place where people can play

import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {

    override func viewDidLoad() {
        view.backgroundColor = .red
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.backgroundColor = .green
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.backgroundColor = .red
    }

}

// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()

In practice, though, you want some additional code to check state, handle touchesCancelled, etc.

This is just to get you going - read up on touch events at: https://developer.apple.com/documentation/uikit/uiview

like image 32
DonMag Avatar answered Dec 27 '22 06:12

DonMag