Return 키를 누를 때 키보드를 숨기는 방법은 무엇입니까?
UITextfied
텍스트 키보드를 클릭 하는 동안 사용 하고 있지만
return
키를 누를 때 키보드가 사라지지 않습니다. 다음 코드를 사용했습니다.
func textFieldShouldReturn(textField: UITextField!) -> Bool // called when 'return' key pressed. return NO to ignore.
{
return true;
}
resignfirstresponder 메소드가 작동하지 않습니다.
다음 기능을 사용하여 앱이 키보드를 닫도록 할 수 있습니다
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
다음은이를 더 잘 설명하기위한 전체 예입니다.
//
// ViewController.swift
//
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet var myTextField : UITextField
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.myTextField.delegate = self
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
}
코드 소스 :
http://www.snip2code.com/Snippet/85930/swift-delegate-sample
이것의
return true
일부는 텍스트 필드에 반환 허용 여부 만 알려줍니다.
키보드 (또는 첫 번째 응답자가 무엇이든)를 닫으려면 텍스트 필드에 수동으로 지시해야하며 이는 다음과 같이 수행됩니다
resignFirstResponder()
.
// Called on 'Return' pressed. Return false to ignore.
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
-
클래스 선언에 추가하십시오 .UITextFieldDelegate
class ViewController: UIViewController, UITextFieldDelegate
-
프로그래밍 방식으로 연결 또는 작성textfield
@IBOutlet weak var userText: UITextField!
- 뷰에서 위임 된 텍스트 필드가로드 될 때 뷰 컨트롤러를 설정하십시오.
override func viewDidLoad() { super.viewDidLoad() self.userText.delegate = self }
- 다음 기능을 추가하십시오
이 모든 것이 있으면 키보드에서 텍스트 필드 외부를 터치하고 Return 키를 눌러도 사라지기 시작합니다.func textFieldShouldReturn(userText: UITextField!) -> Bool { userText.resignFirstResponder() return true; }
Simple Swift 3 솔루션 :이 기능을 텍스트 필드가있는 뷰 컨트롤러에 추가하십시오.
@IBAction func textField(_ sender: AnyObject) {
self.view.endEditing(true);
}
그런 다음 보조 편집기를 열고 Main.storyboard가보기의 한쪽에 있고 원하는 view controller.swift 파일이 다른쪽에 있는지 확인하십시오. 텍스트 필드를 클릭 한 다음 오른쪽 유틸리티 패널에서 '연결 관리자 표시'탭을 선택하십시오. '끝낼 때 끝'에서 빠른 파일의 위 기능으로 드래그를 제어합니다. 해당 장면의 다른 텍스트 필드에 대해 반복하고 동일한 기능에 연결하십시오.
스위프트 4.2-델리게이트 불필요
You can create an action outlet from the UITextField for the "Primary Action Triggered" and resign first responder on the sender parameter passed in:
@IBAction func done(_ sender: UITextField) {
sender.resignFirstResponder()
}
Super simple.
(Thanks to Scott Smith's 60-second video for tipping me off about this: https://youtu.be/v6GrnVQy7iA)
@RSC
for me the critical addition in Xcode Version 6.2 (6C86e) is in override func viewDidLoad()
self.input.delegate = self;
Tried getting it to work with the return key for hours till I found your post, RSC. Thank you!
Also, if you want to hide the keyboard if you touch anywhere else on the screen:
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { self.view.endEditing(true); }
To get automatic keyboard dismissal, I put this code inside one of the methods of my custom text field's class:
textField.addTarget(nil, action:"firstResponderAction:", forControlEvents:.EditingDidEndOnExit)
Substitute your outlet's name for textField
.
Another way of doing this which mostly uses the storyboard and easily allows you to have multiple text fields is:
@IBAction func resignKeyboard(sender: AnyObject) {
sender.resignFirstResponder()
}
Connect all your text fields for that view controller to that action on the Did End On Exit
event of each field.
When the user taps the Done button on the text keyboard, a Did End On Exit event will be generated; at that time, we need to tell the text field to give up control so that the keyboard will go away. In order to do that, we need to add an action method to our controller class. Select ViewController.swift add the following action method:
@IBAction func textFieldDoneEditing(sender: UITextField) {
sender.resignFirstResponder()}
Select Main.storyboard in the Project Navigator and bring up the connections inspector. Drag from the circle next to Did End On Exit to the yellow View Controller icon in the storyboard and let go. A small pop-up menu will appear containing the name of a single action, the one we just added. Click the textFieldDoneEditing action to select it and that's it.
I would sugest to init the Class from RSC:
import Foundation
import UIKit
// Don't forget the delegate!
class ViewController: UIViewController, UITextFieldDelegate {
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@IBOutlet var myTextField : UITextField?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.myTextField.delegate = self;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(textField: UITextField!) -> Bool {
self.view.endEditing(true);
return false;
}
}
Here's the Swift 3.0 update to peacetype's comment:
textField.addTarget(nil, action:Selector(("firstResponderAction:")), for:.editingDidEndOnExit)
Swift 3
Add this code below to your VC
//hide keyboard when user tapps on return key on the keyboard
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true);
return false;
}
Works for me
Swift
Using optional function from UITextFieldDelegate
.
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return textField.endEditing(false)
}
false
means that field can be ask to resign. true
– force resign.
Make sure that your textField delegate is set to the view controller from which you are writing your textfield related code in.
self.textField.delegate = self
you can put this anywhere but not in a UIButton
func TextFieldEndEditing(text fiend name: UITextField!) -> Bool
{
return (false)
}
then you can put this code in a button(also for example):
self.view.endEditing(true)
this worked for me
In the view controller you are using:
//suppose you are using the textfield label as this
@IBOutlet weak var emailLabel: UITextField!
@IBOutlet weak var passwordLabel: UITextField!
//then your viewdidload should have the code like this
override func viewDidLoad() {
super.viewDidLoad()
self.emailLabel.delegate = self
self.passwordLabel.delegate = self
}
//then you should implement the func named textFieldShouldReturn
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
// -- then, further if you want to close the keyboard when pressed somewhere else on the screen you can implement the following method too:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true);
}
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action: #selector(handleScreenTap(sender:)))
self.view.addGestureRecognizer(tap)}
then you use this function
func handleScreenTap(sender: UITapGestureRecognizer) {
self.view.endEditing(true)
}
I hate to add the same function to every UIViewController. By extending UIViewController to support UITextFieldDelegate, you can provide a default behavior of "return pressed".
extension UIViewController: UITextFieldDelegate{
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true;
}
}
When you create new UIViewController and UITextField, all you have to do is to write one line code in your UIViewController.
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self
}
You can even omit this one line code by hooking delegate in Main.storyboard. (Using "ctrl" and drag from UITextField to UIViewController)
참고URL : https://stackoverflow.com/questions/24180954/how-to-hide-keyboard-in-swift-on-pressing-return-key
'programing' 카테고리의 다른 글
Angular 2 베타 17 : 'map'속성이 'Observable'유형에 없습니다. (0) | 2020.05.12 |
---|---|
문자열은 변경할 수 없습니다. (0) | 2020.05.12 |
Django로 이메일 템플릿 만들기 (0) | 2020.05.12 |
오류 : 접두사가 llvm 인 ABI의 NDK 도구 체인 폴더에 도구 체인이 없습니다. (0) | 2020.05.12 |
jQuery없이 urlencoded 양식 데이터를 $ http로 어떻게 POST합니까? (0) | 2020.05.12 |