Programming

UITextField의 커서를 숨 깁니다.

procodes 2020. 7. 10. 21:44
반응형

UITextField의 커서를 숨 깁니다.


내가 사용하고 UITextFieldUIPickerView의에 대한 inputView그래서 사용자가 텍스트 필드를 탭하면 선택기 그들을 위해 소환되는 것을에서 옵션을 선택합니다.

거의 모든 것이 작동하지만 한 가지 문제가 있습니다. 사용자가 필드에 입력 할 것으로 예상되지 않고 키보드가 표시되지 않기 때문에 커서가 여전히 활성화되어있을 때 커서가 여전히 텍스트 필드에서 깜박입니다. 텍스트 필드에서 설정 editing하고 NO터치를 추적하거나 사용자 지정 스타일 버튼으로 바꾸고 코드를 통해 선택기를 소환 하여이 문제를 해킹 할 수 있다는 것을 알고 있습니다. 그러나 UITextFieldDelegate텍스트 필드의 모든 이벤트 처리에 메소드 를 사용 하고 텍스트 필드를 버튼으로 바꾸는 것과 같은 해킹은이 접근법을 허용하지 않습니다.

UITextField대신 커서를 어떻게 숨길 수 있습니까?


UITextField를 서브 클래스로 만들고 caretRectForPosition을 재정의하십시오.

- (CGRect)caretRectForPosition:(UITextPosition *)position
{
    return CGRectZero;
}

iOS 7부터는 tintColor = [UIColor clearColor]textField를 설정 하면 캐럿이 사라집니다.


텍스트 필드의 색조를 지울 수 있습니다.

self.textField.tintColor = [UIColor clearColor];

스위프트 3.0

self.textField.tintColor = .clear

여기에 이미지 설명을 입력하십시오


텍스트 입력 만 피커보기에서 나오도록 사용자가 텍스트를 선택, 복사 또는 붙여 넣기하지 못하게 할 수도 있습니다.

- (CGRect) caretRectForPosition:(UITextPosition*) position
{
    return CGRectZero;
}

- (NSArray *)selectionRectsForRange:(UITextRange *)range
{
    return nil;
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    if (action == @selector(copy:) || action == @selector(selectAll:) || action == @selector(paste:))
    {
        returnNO;
    }

    return [super canPerformAction:action withSender:sender];
}

http://b2cloud.com.au/tutorial/disabling-the-caret-and-text-entry-in-uitextfields/


아웃 확인 재산 selectedTextRange프로토콜 UITextInput ,에 클래스 UITextField 부합 함을 선언합니다. 조금! 바로 객체 지향 프로그래밍에 대한 교훈입니다.

캐럿 숨기기

캐럿을 숨기려면 텍스트 필드의 선택된 텍스트 범위를 생략하십시오.

textField.selectedTextRange = nil; // hides caret

캐럿 숨기기 해제

캐럿 숨기기를 해제하는 두 가지 방법이 있습니다.

  1. Set the text field's selected text range to the end of the document.

    UITextPosition *end = textField.endOfDocument;
    textField.selectedTextRange = [textField textRangeFromPosition:end
                                                        toPosition:end];
    
  2. To keep the caret in the same spot, first, store the text field's selected text range to an instance variable.

    _textFieldSelectedTextRange = textField.selectedTextRange;
    textField.selectedTextRange = nil; // hides caret
    

    Then, when you want to unhide the caret, simply set the text field's selected text range back to what it was originally:

    textField.selectedTextRange     = _textFieldSelectedTextRange;
    _textFieldLastSelectedTextRange = nil;
    

Answer provided by the OP, copied from the question body to help clean up the ever growing tail of unanswered questions.

I found another solution: subclass UIButton and override these methods

- (UIView *)inputView {
    return inputView_;
}

- (void)setInputView:(UIView *)anInputView {
    if (inputView_ != anInputView) {
        [inputView_ release];
        inputView_ = [anInputView retain];
    }
}

- (BOOL)canBecomeFirstResponder {
    return YES;
}

Now the button, as a UIResponder, have a similar behavior than UITextField and an implementation pretty straightforward.


Swift 3 version of Net's post

  override func caretRect(for position: UITextPosition) -> CGRect {
    return .zero
  }

  override func selectionRects(for range: UITextRange) -> [Any] {
    return []
  }

  override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
    return false
  }

set the tintColor to Clear Color

textfield.tintColor = [UIColor clearColor];

and you can also set from the interface builder


Answer provided by the OP, copied from the question body to help clean up the ever growing tail of unanswered questions.

I think I have the correct solution but If it can be improved will be welcome :) Well, I made a subclass of UITextField and overriden the method that returns the CGRect for the bounds

-(CGRect)textRectForBounds:(CGRect)bounds {
    return CGRectZero;
}

The problem? The text doesn't show because the rect is zero. But I added an UILabel as a subview of the control and overridden the setText method so, as we enter a text as usual, the text field text is nil and is the label which shows the text

- (void)setText:(NSString *)aText {
    [super setText:nil];

    if (aText == nil) {
        textLabel_.text = nil;
    }

    if (![aText isEqualToString:@""]) {
        textLabel_.text = aText;
    }
}

With this the thing works as expected. Have you know any way to improve it?


If you want to hide cursor, you can easily use this! It worked for me..

[[textField valueForKey:@"textInputTraits"] setValue:[UIColor clearColor] forKey:@"insertionPointColor"]

To both disable cursor and menu I use subclass with these 2 methods:

- (CGRect)caretRectForPosition:(UITextPosition *)position {
    return CGRectZero;
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    [UIMenuController sharedMenuController].menuVisible = NO;
    self.selectedTextRange = nil;

    return NO;
}

I simply subclass UITextField, and override layoutSubviews as follows:

- (void)layoutSubviews
{
    [super layoutSubviews];
    for (UIView *v in self.subviews)
    {
        if ([[[v class] description] rangeOfString:@"UITextSelectionView"].location != NSNotFound)
        {
            v.hidden = YES;
        }
    }
}

It's a dirty hack, and may fail in the future (at which point the cursor will be visible again - your app won't crash), but it works.


You can add a BOOL cursorless property to UITextField in a category via associated objects.

@interface UITextField (Cursorless)

@property (nonatomic, assign) BOOL cursorless;

@end

Then use method swizzling to swizzle caretRectForPosition: with a method that toggles between CGRectZero and its default value using cursorless.

This leads to a simple interface via a drop-in category. This is demonstrated in the following files.

Simply drop them in and get the benefit of this simple interface

UITextField category: https://github.com/rexmas/RexDK/blob/master/RexDK/UI/UITextField%2BRXCursorless.h https://github.com/rexmas/RexDK/blob/master/RexDK/UI/UITextField%2BRXCursorless.m

스위블 방식 : https://github.com/rexmas/RexDK/blob/master/RexDK/Foundation/NSObject%2BRXRuntimeAdditions.h https://github.com/rexmas/RexDK/blob/master/RexDK/Foundation/NSObject% 2BRXRuntimeAdditions.m

참고 URL : https://stackoverflow.com/questions/3699727/hide-the-cursor-of-an-uitextfield

반응형