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

时间:2017-12-12 15:50:32

标签: ios swift uiview

我希望在按下后突出显示Public Function varBubbleSort(varTempArray As Object) As Object Dim varTemp As Object Dim lngCounter As Long Dim blnNoExchanges As Boolean Do blnNoExchanges = True For lngCounter = 0 To varTempArray.Count - 2 If varTempArray(lngCounter) > varTempArray(lngCounter + 1) Then blnNoExchanges = False Set varTemp = varTempArray(lngCounter) varTempArray(lngCounter) = varTempArray(lngCounter + 1) varTempArray(lngCounter + 1) = varTemp End If Next lngCounter Loop While Not (blnNoExchanges) Set varBubbleSort = varTempArray On Error GoTo 0 Exit Function End Function 并在释放后恢复正常颜色。这样做的最佳做法是什么?

2 个答案:

答案 0 :(得分:4)

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

    }

}

Apple关于覆盖touchesBegantouchesEnded

  

创建自己的子类时,请调用super来转发任何事件   你没有处理自己。如果没有覆盖此方法   调用super(常用模式),你还必须覆盖另一个   处理触摸事件的方法,即使您的实现也是如此   什么都没有。

此示例仅说明了您的问题。子类化UIView可以变得相对复杂,所以这里有几个很好的起点:

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

Proper practice for subclassing UIView?

答案 1 :(得分:1)

非常简单的示例 - 您可以在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