Nice programing

사용자가 UILabel에서 복사 할 텍스트를 선택하도록 허용

nicepro 2021. 1. 6. 20:47
반응형

사용자가 UILabel에서 복사 할 텍스트를 선택하도록 허용


이 질문에 이미 답변이 있습니다.

UILabel이 있지만 사용자가 텍스트의 일부를 선택하도록 허용하려면 어떻게해야합니까? 사용자가 텍스트를 편집하거나 레이블 / 텍스트 필드에 테두리가있는 것을 원하지 않습니다.


에서는 불가능합니다 UILabel.

그것을 위해 사용해야 UITextField합니다. textFieldShouldBeginEditing위임 방법을 사용하여 편집을 비활성화하십시오 .


UITextView를 만들고 .editableNO로 만듭니다. 그런 다음 (1) 사용자가 편집 할 수없는 (2) 테두리가없고 (3) 사용자가 텍스트를 선택할 수있는 텍스트보기가 있습니다.


가난한 사람의 복사 및 붙여 넣기 버전은 텍스트보기를 사용할 수 없거나 사용할 필요가없는 경우 제스처 인식기를 레이블에 추가 한 다음 전체 텍스트를 대지에 복사하는 것입니다. 사용하지 않는 한 일부만 수행 할 수 없습니다.UITextView

사용자에게 복사되었음을 알리고 텍스트의 일부를 강조 표시하려는 사용자를 선택하므로 한 번의 탭 제스처와 길게 누르기를 모두 지원하는지 확인하십시오. 다음은 시작하는 데 도움이되는 몇 가지 샘플 코드입니다.

레이블을 만들 때 제스처 인식기를 등록하십시오.

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textTapped:)];
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(textPressed:)];
                [myLabel addGestureRecognizer:tap];
                [myLabel addGestureRecognizer:longPress];
                [myLabel setUserInteractionEnabled:YES];

다음은 제스처를 처리합니다.

- (void) textPressed:(UILongPressGestureRecognizer *) gestureRecognizer {
    if (gestureRecognizer.state == UIGestureRecognizerStateRecognized &&
        [gestureRecognizer.view isKindOfClass:[UILabel class]]) {
        UILabel *someLabel = (UILabel *)gestureRecognizer.view;
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        [pasteboard setString:someLabel.text];
        ...
        //let the user know you copied the text to the pasteboard and they can no paste it somewhere else
        ...
    }
}

- (void) textTapped:(UITapGestureRecognizer *) gestureRecognizer {
    if (gestureRecognizer.state == UIGestureRecognizerStateRecognized &&
        [gestureRecognizer.view isKindOfClass:[UILabel class]]) {
            UILabel *someLabel = (UILabel *)gestureRecognizer.view;
            UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
            [pasteboard setString:someLabel.text];
            ...
            //let the user know you copied the text to the pasteboard and they can no paste it somewhere else
            ...
    }
}

참조 URL : https://stackoverflow.com/questions/4091053/allow-user-to-select-text-from-uilabel-to-copy

반응형