iOS 에서 UIKeyInput 을 사용 하여 암호 입력 상 자 를 사용자 정의 하 는 방법 예시

머리말
개발 중 에는 비밀번호 입력 이 많은 곳 이 있 는데 이 럴 때 는 UI 디자인 에 따라 사용자 정의 가 필요 하 다.여기 서 UIKeyInput 을 준수 하여 프로 토 콜 의 방법 을 실현 하고 사용자 정의 View 가 텍스트 입력 을 할 수 있 도록 합 니 다.사용자 정의 UI 를 func draw(_ rect: CGRect) 으로 그립 니 다.설정 클래스 를 사용 하여 인 터 페 이 스 를 통일 합 니 다.프 록 시 를 사용 하여 각종 입력 과 관련 된 이 벤트 를 관리 합 니 다.글 말미 에는 OC 와 Swift 의 이중 언어 를 제공 하 는 CLDemo 다운로드 가 있 는데 여기 서 설명 하면 Swift 를 사용한다.
1.UIKeyInput 프로 토 콜 을 준수 하여 텍스트 입력 실현
UIKeyInput 협 의 를 준수 하여 협의 중의 - (BOOL)hasText, - (void)insertText:(NSString *)text,- (void)deleteBackward 이라는 세 가지 방법 을 실현 한다.
여 기 는 읽 기 편 하고 단독으로 분리 하여 하나의 extension 이 된다.

extension CLPasswordInputView: UIKeyInput {
 var hasText: Bool {
  return text.length > 0
 }
 
 func insertText(_ text: String) {
  if self.text.length < config.passwordNum {
   let cs = NSCharacterSet.init(charactersIn: "0123456789").inverted
   let string = text.components(separatedBy: cs).joined(separator: "")
   let basicTest = text == string
   if basicTest {
    self.text.append(text)
    delegate?.passwordInputViewDidChange(passwordInputView: self)
    if self.text.length == config.passwordNum {
     delegate?.passwordInputViewCompleteInput(passwordInputView: self)
    }
    setNeedsDisplay()
   }
  }
 }
 
 func deleteBackward() {
  if text.length > 0 {
   text.deleteCharacters(in: NSRange(location: text.length - 1, length: 1))
   delegate?.passwordInputViewDidChange(passwordInputView: self)
  }
  delegate?.passwordInputViewDidDeleteBackward(passwordInputView: self)
  setNeedsDisplay()
 }
}
2.다시 쓰기 override func draw(rect:CGRect),사용자 정의 UI 그리 기
설정 정보 와 현재 텍스트 입력 에 따라 사용자 정의 UI 를 그립 니 다.그림 코드 와 기본 코드 를 함께 쓰 고 extension 으로 따로 추출 합 니 다.

extension CLPasswordInputView {
 override func becomeFirstResponder() -> Bool {
  if !isShow {
   delegate?.passwordInputViewBeginInput(passwordInputView: self)
  }
  isShow = true;
  return super.becomeFirstResponder()
 }
 override func resignFirstResponder() -> Bool {
  if isShow {
   delegate?.passwordInputViewEndInput(passwordInputView: self)
  }
  isShow = false
  return super.resignFirstResponder()
 }
 var keyboardType: UIKeyboardType {
  get {
   return .numberPad
  }
  set {
   
  }
 }
 override var canBecomeFirstResponder: Bool {
  return true
 }
 override var canResignFirstResponder: Bool {
  return true
 }
 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
  super.touchesBegan(touches, with: event)
  if !isFirstResponder {
   _ = becomeFirstResponder()
  }
 }
 func updateWithConfig(config: ((CLPasswordInputViewConfigure) -> Void)?) -> Void {
  config?(self.config)
  backgroundColor = self.config.backgroundColor
  setNeedsDisplay()
 }
 override func layoutSubviews() {
  super.layoutSubviews()
  setNeedsDisplay()
 }
 override func draw(_ rect: CGRect) {
  let height = rect.size.height
  let width = rect.size.width
  let squareWidth = min(max(min(height, config.squareWidth), config.pointRadius * 4), height)
  let pointRadius = min(config.pointRadius, squareWidth * 0.5) * 0.8
  let middleSpace = CGFloat(width - CGFloat(config.passwordNum) * squareWidth) / CGFloat(CGFloat(config.passwordNum - 1) + config.spaceMultiple * 2)
  let leftSpace = middleSpace * config.spaceMultiple
  let y = (height - squareWidth) * 0.5
  
  let context = UIGraphicsGetCurrentContext()
  
  for i in 0 ..< config.passwordNum {
   context?.addRect(CGRect(x: leftSpace + CGFloat(i) * squareWidth + CGFloat(i) * middleSpace, y: y, width: squareWidth, height: squareWidth))
   context?.setLineWidth(1)
   context?.setStrokeColor(config.rectColor.cgColor)
   context?.setFillColor(config.rectBackgroundColor.cgColor)
  }
  context?.drawPath(using: .fillStroke)
  context?.setFillColor(config.pointColor.cgColor)
  
  for i in 0 ..< text.length {
   context?.addArc(center: CGPoint(x: leftSpace + CGFloat(i + 1) * squareWidth + CGFloat(i) * middleSpace - squareWidth * 0.5, y: y + squareWidth * 0.5), radius: pointRadius, startAngle: 0, endAngle: .pi * 2, clockwise: true)
   context?.drawPath(using: .fill)
  }
 }
}
3.설정 클래스 를 사용 하여 인 터 페 이 스 를 통일 하고 기본 설정 정 보 를 생 성 합 니 다.
사용자 정의 UI 과정 에서 색상,간극,원점 크기 등에 대해 인 터 페 이 스 를 남 겨 외부 수정 에 편리 하도록 해 야 합 니 다.많은 속성 은 사용자 에 게 우호 적 이지 않다.왜냐하면 그 는 어떤 속성 이 필요 하고 어떤 것 이 필요 한 지 모 르 기 때문이다.사용자 가 편리 하 게 사용 할 수 있 도록 여 기 는 설정 정보 류 를 따로 추출 하여 내부 에서 기본 설정 을 실현 하 는 동시에 방법 을 제시 하여 외부 에서 특정한 속성 을 수정 할 수 있 도록 한다.

class CLPasswordInputViewConfigure: NSObject {
 ///     
 var passwordNum: UInt = 6
 ///        
 var squareWidth: CGFloat = 50
 ///     
 var pointRadius: CGFloat = 18 * 0.5
 ///          
 var spaceMultiple: CGFloat = 5;
 ///    
 var pointColor: UIColor = UIColor.black
 ///    
 var rectColor: UIColor = UIColor.lightGray
 ///       
 var rectBackgroundColor: UIColor = UIColor.white
 ///      
 var backgroundColor: UIColor = UIColor.white
 
 class func defaultConfig() -> CLPasswordInputViewConfigure {
  let configure = CLPasswordInputViewConfigure()
  return configure
 }
}
외부 에서 설정 을 수정 하 는 방법 은 패 키 지 를 사용 하여 기본 설정 을 외부 로 되 돌리 고 외부 에서 이 속성 을 수정 한 후 내부 UI 를 새로 고 칩 니 다.

func updateWithConfig(config: ((CLPasswordInputViewConfigure) -> Void)?) -> Void {
  config?(self.config)
  backgroundColor = self.config.backgroundColor
  setNeedsDisplay()
 }
4.프 록 시 를 사용 하여 각종 입력 과 관련 된 이 벤트 를 관리 합 니 다.
여기 서 하나의 프로 토 콜 을 만 들 고 각종 입력 이 벤트 를 관리 하 는 동시에 extension 을 통 해 이 프로 토 콜 을 실현 하면 외부 에서 반드시 실현 해 야 하 는 것 이 아니 라 선택적으로 이 프로 토 콜 을 실현 할 수 있 습 니 다.

protocol CLPasswordInputViewDelegate {
 ///    
 func passwordInputViewDidChange(passwordInputView:CLPasswordInputView) -> Void
 ///    
 func passwordInputViewDidDeleteBackward(passwordInputView:CLPasswordInputView) -> Void
 ///    
 func passwordInputViewCompleteInput(passwordInputView:CLPasswordInputView) -> Void
 ///    
 func passwordInputViewBeginInput(passwordInputView:CLPasswordInputView) -> Void
 ///    
 func passwordInputViewEndInput(passwordInputView:CLPasswordInputView) -> Void
}

extension CLPasswordInputViewDelegate {
 ///    
 func passwordInputViewDidChange(passwordInputView:CLPasswordInputView) -> Void {
  
 }
 ///    
 func passwordInputViewDidDeleteBackward(passwordInputView:CLPasswordInputView) -> Void {
  
 }
 ///    
 func passwordInputViewCompleteInput(passwordInputView:CLPasswordInputView) -> Void {
  
 }
 ///    
 func passwordInputViewBeginInput(passwordInputView:CLPasswordInputView) -> Void {
  
 }
 ///    
 func passwordInputViewEndInput(passwordInputView:CLPasswordInputView) -> Void {
  
 }
}
5.효과 도
여기 서 간단하게 녹음 한 효과 가 있 습 니 다.더 많은 것 은 CLDemo 을 참고 하 시기 바 랍 니 다. ( 로 컬 다운로드

효과 도.gif
6.총화
여러분 의 학습 편 의 를 위해 OC 와 Swift 두 가지 언어 가 각각 실 현 된--->>>CLDemo 을 제공 합 니 다. ( 로 컬 다운로드)도움 이 된다 면 스타 를 환영 합 니 다.
자,이상 이 이 글 의 전체 내용 입 니 다.본 논문 의 내용 이 여러분 의 학습 이나 업무 에 어느 정도 참고 학습 가치 가 있 기 를 바 랍 니 다.궁금 한 점 이 있 으 시 면 댓 글 을 남 겨 주 셔 서 저희 에 대한 지지 에 감 사 드 립 니 다.

좋은 웹페이지 즐겨찾기