从视图控制器外部的函数ResignFirstResponder

时间:2017-01-08 07:45:37

标签: ios uitextfield uipickerview resignfirstresponder

我目前正与import sys import os import socket s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serveraddress = ('localhost' , 2000) print ('connecting to server on'), serveraddress s1.connect(serveraddress) try: a = input('Enter you choice: \n 1-Get file \n 2-Get List \n 3-quit \n') while True: if a == 1: s1.send('1') b = input('enter file name: ') s1.send(b) downloadDir = r'C:\Users\rahul\Desktop' with open(os.path.join(downloadDir, b), 'wb') as filetowrite: while True: data = s1.recv(1000) if not data: break filetowrite.write(data) filetowrite.close() s1.close() elif a == 2: s1.send('2') #s1.sendall(' send all files list ') filelist = s1.recv(1000) print (filelist) elif a == 3: x = False print('closing connection') s1.close() finally: s1.close 一起使用输入视图 - UITextField,并在UIPickerView的顶部添加了一个完成按钮。我可以使用完成按钮关闭选择器视图,方法是使用

从视图控制器类中重新设置文本字段的第一个响应者
UIPickerView

问题是我想在viewController类外面调用一个函数来调用let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.dismissPickerView)) func dismissPickerView() { myTextField.resignFirstResponder } 上的第一个响应者,如下所示

myTextField

所以我可以将它用于多个选择器视图,但我不知道如何实现“func doneButton (viewcontroller: UIViewController,textfield:UITextField) { let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(textfield.resignFirstResponder)) } ”的选择器

任何反馈都会提供帮助

1 个答案:

答案 0 :(得分:0)

您创建一个帮助器单例类,它将观察UITextFieldTextDidBeginEditingNotification,UITextFieldTextDidEndEditingNotification。 在发出通知时存储/清除文本字段或任何其他第一响应者对象的引用

向单例类添加静态或对象方法,该方法将在先前从通知中存储的对象上重新签署第一响应者

Swift 3.0

class KeyBoardHelper {

var firstResponder:UIView?

static let sharedInstance = KeyBoardHelper()

static func initializedInstance()
{
    _ = sharedInstance
}

init()
{
    print("Start listning for keyboard event")

    NotificationCenter.default.addObserver(self, selector: #selector(KeyBoardHelper.keyboardWillShow(notification:)), name: NSNotification.Name.UITextFieldTextDidBeginEditing, object: nil)

    NotificationCenter.default.addObserver(self, selector: #selector(KeyBoardHelper.keyboardWillHide(notification:)), name: NSNotification.Name.UITextViewTextDidEndEditing, object: nil)
}

@objc func keyboardWillShow(notification:Notification)
{
    firstResponder = notification.object as? UIView
}

@objc func keyboardWillHide(notification:Notification)
{
    firstResponder = nil
}


static func resignKeyboard()
{
    KeyBoardHelper.sharedInstance.firstResponder?.resignFirstResponder()
}

@objc func dismissKeyboard()
{
    firstResponder?.resignFirstResponder()
}

static func resignBarButton() -> UIBarButtonItem
{
    let barButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: KeyBoardHelper.sharedInstance, action: #selector(KeyBoardHelper.dismissKeyboard))
    return barButton
}

}