[iOS] UILabel 텍스트 복사

doooly·2023년 8월 31일
0

iOS

목록 보기
5/8

UILabel

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

[ UILabel을 눌렀을 때, Label에 있는 string을 바로 복사하는 방법 ]


1. UITapGestureRecognizer 사용

func CopyLabel() {
	        let tap = UITapGestureRecognizer(target: self, action: #selector(labelTapped(sender:)))
	        self.isUserInteractionEnabled = true
	        self.addGestureRecognizer(tap) 
	    }
  • tap이라는UITapGestureRecognizer 상수를 만든다

  • isUserInteractionEnabled을 true로 지정한다
    https://developer.apple.com/documentation/uikit/uiview/1622577-isuserinteractionenabled

    When set to false, touch, press, keyboard, and focus events intended for the view are ignored and removed from the event queue. When set to true, events are delivered to the view normally. The default value of this property is true.
    During an animation, user interactions are temporarily disabled for all views involved in the animation, regardless of the value in this property. You can disable this behavior by specifying the allowUserInteraction option when configuring the animation.

    False로 설정하면 터치 등의 이벤트가 무시되기 때문에, 이벤트를 정상적으로 뷰로 전달하기 위해 True로 지정한다

  • Label에 addGestureRecognizer을 통해 tap을 붙인다
    이를 통해 label에서 gesture을 인식할 수 있다

2. action

UITapGestureRecongnizer이 Label에 전달될 때 취하게 될 액션을 정의한 함수이다
아래는 sender의 string을 클립보드에 복사하는 과정이다.

  @objc private func labelTapped(sender: UITapGestureRecognizer) {
	        guard let label = sender.view as? UILabel else {
	            return
	        }
	        UIPasteboard.general.string = label.text
	    }




[ 전체 코드 ]

UILabel에 공통적으로 기능을 추가하기 위해, UILabel에 extension을 이용해 함수를 작성했다

extension UILabel {
	func CopyLabel() {
	        let tap = UITapGestureRecognizer(target: self, action: #selector(labelTapped(sender:)))
	        self.isUserInteractionEnabled = true
	        self.addGestureRecognizer(tap) 
	    }
	    
	    @objc private func labelTapped(sender: UITapGestureRecognizer) {
	        guard let label = sender.view as? UILabel else {
	            return
	        }
	        UIPasteboard.general.string = label.text 
	    }
}

출처
https://yoojin99.github.io/app/UILabel-터치해서-text-복사/

0개의 댓글