Programing

UITextField가 변경 될 때 어떻게 확인합니까?

lottogame 2020. 4. 1. 07:57
반응형

UITextField가 변경 될 때 어떻게 확인합니까?


텍스트 필드가 변경되는 시점을 확인하려고하는데 textView에 사용되는 기능과 동일 textViewDidChange합니다.

  func textFieldDidBeginEditing(textField: UITextField) {
        if self.status.text == "" && self.username.text == "" {
            self.topRightButton.enabled = false
        } else {   
            self.topRightButton.enabled = true
        }
    }

어떤 종류의 작품이지만 topRightButton텍스트 필드를 누르 자마자 활성화되어 있습니까? 텍스트를 실제로 입력 할 때만 활성화하고 싶습니다.


빠른

스위프트 4.2

textfield.addTarget(self, action: #selector(ViewControllerr.textFieldDidChange(_:)), for: UIControl.Event.editingChanged)

@objc func textFieldDidChange(_ textField: UITextField) {

}

스위프트 3 & 스위프트 4.1

textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)

func textFieldDidChange(_ textField: UITextField) {

}

스위프트 2.2

textField.addTarget(self, action: #selector(YourViewController.textFieldDidChange(_:)), forControlEvents: UIControlEvents.EditingChanged)

func textFieldDidChange(textField: UITextField) {
    //your code
}

목표 -C

[textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

textFieldDidChange 메소드는

-(void)textFieldDidChange :(UITextField *) textField{
    //your code
}

인터페이스 빌더에서이 연결을 작성할 수 있습니다.

  1. 스토리 보드에서 화면 상단의 보조 편집기 (가운데에 두 개의 원)를 클릭하십시오. 어시스턴트 에디터 선택

  2. 인터페이스 빌더에서 텍스트 필드를 Ctrl + 클릭하십시오.

  3. 보조자보기의 EditingChanged에서 뷰 컨트롤러 클래스 내부로 드래그하십시오. 연결하기

  4. 함수 이름을 지정하고 (예 : "textDidChange") 연결을 클릭하십시오. 명명 기능


스위프트 3.0

textField.addTarget(self, action: #selector(textFieldDidChange(textField:)), for: .editingChanged)

처리 방법 :

func textFieldDidChange(textField: UITextField) { 

}

스위프트 4.0

textField.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)),
                          for: UIControlEvents.editingChanged)

처리 방법 :

@objc func textFieldDidChange(_ textField: UITextField) {

}

스위프트 5.0

textField.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)),
                          for: UIControl.Event.editingChanged)

처리 방법 :

@objc func textFieldDidChange(_ textField: UITextField) {

}

내가 지금까지 처리 한 방식 : UITextFieldDelegate

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
    // text hasn't changed yet, you have to compute the text AFTER the edit yourself
    let updatedString = (textField.text as NSString?)?.stringByReplacingCharactersInRange(range, withString: string)

    // do whatever you need with this updated string (your code)


    // always return true so that changes propagate
    return true
}

스위프트 4 버전

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let updatedString = (textField.text as NSString?)?.replacingCharacters(in: range, with: string)
    return true
}

스위프트 3

 textField.addTarget(self, action: #selector(ViewController.textFieldDidChange(sender:)), for: UIControlEvents.editingChanged)

스위프트 3.0.1+ (다른 신속한 3.0 답변 중 일부는 최신이 아닙니다)

textField.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)),
                          for: UIControlEvents.editingChanged)

func textFieldDidChange(_ textField: UITextField) {

}

textField (_ : shouldChangeCharactersIn : replacementString :) 은 모든 키 누름을 확인하려면 Xcode 8, Swift 3에서 저에게 효과적이었습니다 .

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    // Whatever code you want to run here.
    // Keep in mind that the textfield hasn't yet been updated,
    // so use 'string' instead of 'textField.text' if you want to
    // access the string the textfield will have after a user presses a key

    var statusText = self.status.text
    var usernameText = self.username.text

    switch textField{
    case self.status:
        statusText = string
    case self.username:
        usernameText = string
    default:
        break
    }

    if statusText == "" && usernameText == "" {
        self.topRightButton.enabled = false
    } else {   
        self.topRightButton.enabled = true
    }

    //Return false if you don't want the textfield to be updated
    return true
}

스위프트 4

UITextFieldDelegate를 준수하십시오 .

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    // figure out what the new string will be after the pending edit
    let updatedString = (textField.text as NSString?)?.replacingCharacters(in: range, with: string)

    // Do whatever you want here


    // Return true so that the change happens
    return true
}

UITextFieldDelegate에서이 대리자 메서드를 사용할 수 있습니다. 캐릭터가 바뀔 때마다 발생합니다.

(Objective C) textField:shouldChangeCharactersInRange:replacementString:
(Swift) textField(_:shouldChangeCharactersInRange:replacementString:)

그러나이 변경은 변경 전에 이루어집니다 (실제로 여기에서 true를 반환하는 경우에만 변경이 이루어집니다).


아마도 RxSwift?

필요한 것

pod 'RxSwift',    '~> 3.0'
pod 'RxCocoa',    '~> 3.0'

수입을 분명히 추가하다

import RxSwift
import RxCocoa

그래서 너는 textfield : UITextField

let observable: Observable<String?> = textField.rx.text.asObservable()
observable.subscribe(
            onNext: {(string: String?) in
                print(string!)
        })

U는 다른 3 가지 방법이 있습니다.

  1. onError
  2. 완료
  3. onDisposed
  4. 다음에

스위프트 4

textField.addTarget(self, action: #selector(textIsChanging), for: UIControlEvents.editingChanged)

@objc func textIsChanging(_ textField:UITextField) {

 print ("TextField is changing")

}

사용자가 완전히 입력 한 후에 변경하려면 키보드를 닫거나 Enter 키를 누르면 호출됩니다.

textField.addTarget(self, action: #selector(textDidChange), for: UIControlEvents.editingDidEnd)

 @objc func textDidChange(_ textField:UITextField) {

       print ("TextField did changed") 
 }

txf_Subject.addTarget(self, action:#selector(didChangeFirstText), for: .editingChanged)

@objc func didChangeText(textField:UITextField) {
    let str = textField.text
    if(str?.contains(" "))!{
        let newstr = str?.replacingOccurrences(of: " ", with: "")
        textField.text = newstr
    }
}

@objc func didChangeFirstText(textField:UITextField) {
    if(textField.text == " "){
        textField.text = ""
    }
}

다음 단계를 따라야합니다.

  1. 텍스트 필드에 대한 아울렛 참조 만들기
  2. 컨트롤러 클래스에 AssignUITextFieldDelegate
  3. yourTextField.delegate를 구성하십시오.
  4. 필요한 기능을 구현하십시오

샘플 코드 :

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet var yourTextFiled : UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        yourTextFiled.delegate = self
    }


    func textFieldDidEndEditing(_ textField: UITextField) {
        // your code
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        // your code
    }

    .
    .
    .
}

Swift 3을textField text change listener 사용하여 추가하는 방법입니다 .

수업을 다음과 같이 선언하십시오. UITextFieldDelegate

override func viewDidLoad() {
    super.viewDidLoad()

    textField.delegate = self

    textField.addTarget(self, action: #selector(UITextFieldDelegate.textFieldShouldEndEditing(_:)), for: UIControlEvents.editingChanged)
}

그런 다음 전통적으로 textFieldShouldEndEditing 함수를 추가하십시오.

func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { // do stuff
        return true 
}

새로운 커스텀 클래스 MaterialTextfield.swift 생성

class MaterialTextfield: UITextField,UITextFieldDelegate {

var bottomBorder = UIView()
var shouldShowEditing = false

override func awakeFromNib() {

    // Setup Bottom-Border

    self.delegate = self
    self.translatesAutoresizingMaskIntoConstraints = false

    bottomBorder = UIView.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
    bottomBorder.backgroundColor = UIColor(rgb: 0xE2DCD1) // Set Border-Color
    bottomBorder.translatesAutoresizingMaskIntoConstraints = false

    addSubview(bottomBorder)

    bottomBorder.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
    bottomBorder.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
    bottomBorder.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
    bottomBorder.heightAnchor.constraint(equalToConstant: 1).isActive = true // Set Border-Strength

}
@IBInspectable var hasError: Bool = false {
    didSet {
        if (hasError) {
            bottomBorder.backgroundColor = UIColor.red//error color
        } else {
            bottomBorder.backgroundColor = UIColor(rgb: 0xE2DCD1)//passive color
        }

    }
}
@IBInspectable var showEditing: Bool = false{
    didSet {
        if (showEditing) {
            bottomBorder.backgroundColor = UIColor(rgb: 0x56B5CA)//active color
        } else {
            bottomBorder.backgroundColor = UIColor(rgb: 0xE2DCD1)//passive color
        }

    }

}

func textFieldDidBeginEditing(_ textField: UITextField) {//listen to on edit event
    showEditing = !self.showEditing
}
func textFieldDidEndEditing(_ textField: UITextField) {//listen to on end edit event
    showEditing = !self.showEditing
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {//listen to return button event
    textField.resignFirstResponder() // return button will close keyboard
    return true
}

}

스위프트 4

viewDidLoad ()에서 :

    //ADD BUTTON TO DISMISS KEYBOARD

    // Init a keyboard toolbar 
    let toolbar = UIView(frame: CGRect(x: 0, y: view.frame.size.height+44, width: view.frame.size.width, height: 44))
    toolbar.backgroundColor = UIColor.clear

    // Add done button
    let doneButt = UIButton(frame: CGRect(x: toolbar.frame.size.width - 60, y: 0, width: 44, height: 44))
    doneButt.setTitle("Done", for: .normal)
    doneButt.setTitleColor(MAIN_COLOR, for: .normal)
    doneButt.titleLabel?.font = UIFont(name: "Titillium-Semibold", size: 13)
    doneButt.addTarget(self, action: #selector(dismissKeyboard), for: .touchUpInside)
    toolbar.addSubview(doneButt)

    USDTextField.inputAccessoryView = toolbar

이 기능을 추가하십시오 :

    @objc func dismissKeyboard() {
      //Causes the view (or one of its embedded text fields) to resign the first responder status.
      view.endEditing(true)
    }

참고 URL : https://stackoverflow.com/questions/28394933/how-do-i-check-when-a-uitextfield-changes

반응형