1. 程式人生 > >UITextField 密碼明文及密文切換問題

UITextField 密碼明文及密文切換問題

1. 使用UITextField設定明文及密文之間切換後,游標的位置可能會出現偏移出錯(因為密文方式佔位符更寬一點)。這個應該是UITextField這個控制元件本身的問題,但好在還是有辦法能解決(治癒強迫症患者的福音偷笑)。

在明文/密文切換的事件裡面,加多幾句話:

- (void)visiblePWBtnAction:(UIButton *)sender
{
    self.passwordTextField.enabled = NO;    // the first one;
    
    self.passwordTextField.secureTextEntry = sender.selected;
    
    sender.selected = !sender.selected;
    
    self.passwordTextField.enabled = YES;  // the second one;
    [self.passwordTextField becomeFirstResponder];    // the third one
}


2. 使用UITextField從明文切換到密文後,輸入任何值都會將密文的輸入先清空。這個是UITextField預設的設定,好像也沒有一個屬性值可以直接控制吧。不過在代理裡面,加多一個判斷也能避免密文清空的問題,如下:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (textField == self.passwordTextField && textField.isSecureTextEntry) {
        textField.text = toBeString;
        return NO;
    }
    
    return YES;
}