programing

컨트롤러의 UIView 터치 이벤트

megabox 2023. 8. 7. 22:26
반응형

컨트롤러의 UIView 터치 이벤트

Xcode가 Main.storyboard에서 제공하지 않기 때문에 UIView touchbegin 액션 또는 터치엔드 액션을 프로그래밍 방식으로 추가하려면 어떻게 해야 합니까?

코드를 통해 추가해야 합니다.먼저 보기를 생성하고 계층에 추가합니다.

var myView = UIView(frame: CGRectMake(100, 100, 100, 100))
self.view.addSubview(myView) 

그런 다음 제스처 인식기를 초기화합니다.스위프트 2까지:

let gesture = UITapGestureRecognizer(target: self, action: "someAction:")

Swift 2 이후:

let gesture = UITapGestureRecognizer(target: self, action:  #selector (self.someAction (_:)))

그런 다음 보기에 바인딩합니다.

self.myView.addGestureRecognizer(gesture)

    

스위프트 3:

func someAction(_ sender:UITapGestureRecognizer){     
  // do other task
}
    

스위프트 4 그냥 추가.@objc전에func:

@objc func someAction(_ sender:UITapGestureRecognizer){     
    // do other task
}

Swift UI:

Text("Tap me!").tapAction {
    print("Tapped!")
}

스위프트 4 / 5:

let gesture = UITapGestureRecognizer(target: self, action:  #selector(self.checkAction))
self.myView.addGestureRecognizer(gesture)

@objc func checkAction(sender : UITapGestureRecognizer) {
    // Do what you want
}

스위프트 3:

let gesture = UITapGestureRecognizer(target: self, action:  #selector(self.checkAction(sender:)))
self.myView.addGestureRecognizer(gesture)

func checkAction(sender : UITapGestureRecognizer) {
    // Do what you want
}

Swift 3.x에 대한 @Crashalot의 답변 업데이트:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.location(in: self)
        // do something with your currentPoint
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.location(in: self)
        // do something with your currentPoint
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.location(in: self)
        // do something with your currentPoint
    }
}

Swift 2.x에 대한 @Chackle의 답변 업데이트:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.locationInView(self)
        // do something with your currentPoint
    }
}

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.locationInView(self)
        // do something with your currentPoint
    }
}

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.locationInView(self)
        // do something with your currentPoint
    }
}

이것을 당신의 안에 넣으세요.UIViewsubclass(이 기능에 대한 subclass를 만드는 것이 가장 쉽습니다).

class YourView: UIView {

  //Define your initialisers here

  override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    if let touch = touches.first as? UITouch {
      let currentPoint = touch.locationInView(self)
      // do something with your currentPoint
    }
  }

  override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
    if let touch = touches.first as? UITouch {
      let currentPoint = touch.locationInView(self)
      // do something with your currentPoint
    }
  }

  override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
    if let touch = touches.first as? UITouch {
      let currentPoint = touch.locationInView(self)
      // do something with your currentPoint
    }
  }
}

스위프트 4용

@IBOutlet weak var someView: UIView!  
let gesture = UITapGestureRecognizer(target: self, action:  #selector (self.someAction (_:)))
self.someView.addGestureRecognizer(gesture)

@objc func someAction(_ sender:UITapGestureRecognizer){
    print("view was clicked")
}

StoryBoard에서 작성된 뷰에서 아웃렛을 작성합니다.

@IBOutlet weak var redView: UIView!
@IBOutlet weak var orangeView: UIView!
@IBOutlet weak var greenView: UIView!   

touchsBegin 메서드를 재정의합니다.두 가지 옵션이 있습니다. 모든 사람이 어떤 것이 자신에게 더 좋은지 결정할 수 있습니다.

  1. 특수 보기에서 터치를 감지합니다.

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
         if let touch = touches.first {
            if touch.view == self.redView {
                tapOnredViewTapped()
            } else if touch.view == self.orangeView {
                orangeViewTapped()
            } else if touch.view == self.greenView {
                greenViewTapped()
            } else {
                return
            }
        }
    
    }
    
  2. 특수 뷰에서 접점을 감지합니다.

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            let location = touch.location(in: view)
            if redView.frame.contains(location) {
                redViewTapped()
            } else if orangeView.frame.contains(location) {
                orangeViewTapped()
            } else if greenView.frame.contains(location) {
                greenViewTapped()
            }
        }
    
    }
    

마지막으로, 사용자가 클릭한 보기에 따라 호출될 함수를 선언해야 합니다.

func redViewTapped() {
    print("redViewTapped")
}

func orangeViewTapped() {
    print("orangeViewTapped")
}

func greenViewTapped() {
    print("greenViewTapped")
}

Swift 4.2:

@IBOutlet weak var viewLabel1: UIView!
@IBOutlet weak var viewLabel2: UIView!
  override func viewDidLoad() {
    super.viewDidLoad()

    let myView = UITapGestureRecognizer(target: self, action: #selector(someAction(_:)))
    self.viewLabel1.addGestureRecognizer(myView)
}

 @objc func someAction(_ sender:UITapGestureRecognizer){
   viewLabel2.isHidden = true
 }

이 방법을 사용하여 확장을 만들 수 있습니다.

extension UIView {
    
    func addTapGesture(action : @escaping ()->Void ){
        let tap = MyTapGestureRecognizer(target: self , action: #selector(self.handleTap(_:)))
        tap.action = action
        tap.numberOfTapsRequired = 1
        
        self.addGestureRecognizer(tap)
        self.isUserInteractionEnabled = true
        
    }
    @objc func handleTap(_ sender: MyTapGestureRecognizer) {
        sender.action!()
    }
}

class MyTapGestureRecognizer: UITapGestureRecognizer {
    var action : (()->Void)? = nil
}

다음과 같이 사용합니다.

@IBOutlet weak var testView: UIView!
testView.addTapGesture{
   // ...
}
    

위의 답변에 대한 업데이트만 하면 됩니다.

클릭 이벤트에서 변경 사항을 확인하려면, 즉 사용자가 UI 보기를 클릭할 때마다 UIVI의 새 색상이 변경되고 아래와 같이 변경합니다.

class ClickableUIView: UIView {
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
            if let touch = touches.first {
                let currentPoint = touch.locationInView(self)
                // do something with your currentPoint
            }

            self.backgroundColor = UIColor.magentaColor()//Color when UIView is clicked.
        }

        override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
            if let touch = touches.first {
                let currentPoint = touch.locationInView(self)
                // do something with your currentPoint
            }

            self.backgroundColor = UIColor.magentaColor()//Color when UIView is clicked.
        }

        override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
            if let touch = touches.first {
                let currentPoint = touch.locationInView(self)
                // do something with your currentPoint
            }

            self.backgroundColor = UIColor.whiteColor()//Color when UIView is not clicked.

}//class closes here

또한 Storyboard & View Controller에서 이 클래스를 다음과 같이 부릅니다.

@IBOutlet weak var panVerificationUIView:ClickableUIView!

Swift 4.x에 대한 @stevo.mit의 응답 업데이트:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.location(in: self.view)
        // do something with your currentPoint
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.location(in: self.view)
        // do something with your currentPoint
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.location(in: self.view)
        // do something with your currentPoint
    }
}

언급URL : https://stackoverflow.com/questions/30505165/uiview-touch-event-in-controller

반응형