iOS UITextField


keyboard 의 return 을 DONE 으로 변경

tfName.returnKeyType = UIReturnKeyType.done

핸들러 연결하는데, Did End On Exit 을 연결해야 return이나 DONE 눌렀을 때, 키보드가 내려간다. 핸들러 안에 아무 내용 없어도 된다.

키보드 위에 툴바에 DONE 버튼 추가하는 방법

extension UITextField{

    @IBInspectable var doneAccessory: Bool{
        get{
            return self.doneAccessory
        }
        set (hasDone) {
            if hasDone{
                addDoneButtonOnKeyboard()
            }
        }
    }

    func addDoneButtonOnKeyboard() {
        let doneToolbar: UIToolbar = UIToolbar(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
        doneToolbar.barStyle = .default

        let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        let done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(self.doneButtonAction))

        let items = [flexSpace, done]
        doneToolbar.items = items
        doneToolbar.sizeToFit()

        inputAccessoryView = doneToolbar
    }

    @objc func doneButtonAction() {
        endEditing(true)
    }

}

IB 에서 메뉴가 생긴다. 거기서 설정하면 툴바에 DONE 생긴다.

,

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다