2017-12-12 8 views

답변

0

아주 간단한 예 - 당신은 놀이터 페이지에서 실행할 수 있습니다 : 실제로

//: 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

1

서브 클래스는 UIView이며 뷰 컨트롤러는 가늘게 유지하십시오. touchesBegantouchesEnded를 오버라이드 (override)에 대한

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 

    } 

} 

애플 :

자신의 서브 클래스를 작성, 당신이 자신을 처리하지 않는 이벤트 을 전달하기 위해 슈퍼를 호출합니다. super (공통 사용 패턴)을 호출하지 않고이 메서드를 재정의하는 경우 구현에서 을 수행하지 않아도 터치 이벤트를 처리하는 다른 메서드를 재정의해야합니다.

이 예는 질문을 보여줍니다.

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

Proper practice for subclassing UIView?