当按下时如何使UIView改变颜色?

5

我想在UIView被按下后突出显示,松开后返回正常颜色。如何最好地实现这个功能?


1
使用 UIButton - rmaddy
2个回答

11

创建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
    }
}

关于重写touchesBegantouchesEnded,苹果公司提供以下建议:

在创建自己的子类时,调用super方法以转发任何您不处理的事件。如果您重写此方法而没有调用super(这是常见的用法模式),则还必须覆盖其他处理触摸事件的方法[即touchesEndedtouchesMovedtouchesCancelled],即使您的实现什么也不做。

进一步阅读:

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

Proper practice for subclassing UIView?


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()

实际上,你需要一些额外的代码来检查状态、处理touchesCancelled等。

这只是为了让你开始学习 - 在以下网址上阅读关于触摸事件的更多信息:https://developer.apple.com/documentation/uikit/uiview


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接