UITextField secureTextEntry - works going from YES to NO, but changing back to YES has no effect

前端 未结 5 1848
无人及你
无人及你 2021-01-31 09:13

The above says it all- I have a UITextField set to secure, but want to give users the option to make it not secure (so they can see for sure what they typed if they are in a pri

5条回答
  •  甜味超标
    2021-01-31 10:00

    I entered rdar against this problem, but did find a work around. Essentially you have to programmatically replace the "stuck" control with a new one. The easiest thing to do is to archive the existing control in viewDidLoad then unarchive as needed:

    // do in viewDidLoad
    self.passwordMemberArchive = [NSMutableData data];
    NSKeyedArchiver *ka = [[NSKeyedArchiver alloc]       initForWritingWithMutableData:passwordMemberArchive];
    [ka encodeObject:password];
    [ka finishEncoding];
    [ka release];
    
    
        // In the action method when you get the UISwitch action message ---
    // when your switch changes state
    if(isOn) {
        NSString *text = [NSString stringWithString:password.text];
        NSKeyedUnarchiver *kua = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
        UITextField *tf = [kua decodeObject];
        [kua finishDecoding];
        [kua release];
        tf.inputAccessoryView = textField.inputAccessoryView;
        tf.frame = textField.frame;
    
        BOOL isFirstResponder = [textField isFirstResponder];
        [scrollView insertSubview:tf aboveSubview:textField];
        if(isFirstResponder) {
            [tf becomeFirstResponder];
        }
    
        [textField removeFromSuperview];
        self.password = tf;
    
        if([text length]) {
            if(isFirstResponder) {
                // http://stackoverflow.com/questions/1317929/insert-string-at-cursor-position-of-uitextfield
                // Get a reference to the system pasteboard
                UIPasteboard* lPasteBoard = [UIPasteboard generalPasteboard];
                // Save the current pasteboard contents so we can restore them later
                NSArray* lPasteBoardItems = [lPasteBoard.items copy];
                // Update the system pasteboard with my string
                lPasteBoard.string = text;
                // Paste the pasteboard contents at current cursor location
                [tf paste:self];
                // Restore original pasteboard contents
                lPasteBoard.items = lPasteBoardItems;
                [lPasteBoardItems release];
            } else {
                tf.text = text;
            }
        }
    } else {
        textField.secureTextEntry = NO;
    }
    

提交回复
热议问题