按下时如何使UIView更改颜色?

Eri*_*kLm 3 uiview ios swift

UIView按下后我想突出显示,放开后恢复为正常颜色。最佳做法是什么?

bso*_*sod 6

子类化UIView,并使您的视图控制器保持精简。

class CustomUIView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)

        backgroundColor = UIColor.blue

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

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

        print("touch start")
        backgroundColor = UIColor.red

    }

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

        print("touch ended")
        backgroundColor = UIColor.blue

    }

}
Run Code Online (Sandbox Code Playgroud)

苹果关于覆盖touchesBegantouchesEnded

创建自己的子类时,请调用super来转发您自己无法处理的所有事件。如果您在不调用super的情况下重写此方法(一种常用模式),则即使您的实现不执行任何操作,也必须重写其他方法来处理触摸事件。

本示例仅说明您的问题。子类化UIView可能会变得相对复杂,因此这里有两个很好的起点:

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

子类化UIView的正确做法?


Don*_*Mag 3

非常简单的示例 - 您可以在 Playground 页面中运行它:

//: 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()
Run Code Online (Sandbox Code Playgroud)

但在实践中,您需要一些额外的代码来检查状态、句柄touchesCancelled等。

这只是为了让您继续前进 - 请阅读有关触摸事件的信息:https ://developer.apple.com/documentation/uikit/uiview