【问题标题】:how to dismiss keyboard iOS on a table view如何在表格视图上关闭键盘 iOS
【发布时间】:2015-03-20 03:52:03
【问题描述】:

当用户触摸它的外部时关闭这个键盘的好方法是什么?我尝试了接触开始的方法,但这不起作用。 textfieldshouldreturn 方法虽然可以正常工作。我想不出任何其他方法来做到这一点。有人可以在这里帮助我吗,我将非常感谢任何帮助。谢谢

import UIKit


var courseCatalog : [String] = Array<String>()


class HomeViewController: UIViewController, UITextFieldDelegate , UITableViewDelegate{

    @IBOutlet var searchTextField: UITextField!


    override func viewDidLoad() {

        courseCatalog = ["Accounting", "Administration" , "American Studies" , "Anthropology" , "Arabic" , "Art" , "Aerospace Studies" , "American Sign Language" , "Biology" , "Child Development" , "Chemistry" , "Chinese" , "Criminal Justice", "Communication Studies" , "Computer Science", "Computer Engineering"]

        super.viewDidLoad()

        println(PFUser.currentUser())

        println("Home Tab View Controller")

        searchTextField.delegate = self
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return courseCatalog.count

    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")

        cell.textLabel?.text = courseCatalog[indexPath.row]

        return cell

    }

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }


    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {


        self.searchTextField.resignFirstResponder()

    }

    func textFieldShouldReturn(textField: UITextField!) -> Bool {

        searchTextField.resignFirstResponder()
        return true

    }





}

【问题讨论】:

标签: ios xcode swift


【解决方案1】:

你应该在你的表格视图中添加一个点击手势识别器,当它被触发时关闭键盘:

//Somewhere in setup
UITapGestureRecognizer *viewTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeyboard)];
viewTap.cancelsTouchesInView = FALSE;
[myTableView addGestureRecognizer:viewTap];

//Somewhere else in your class
-(void)closeKeyboard {

    [self.view endEditing:TRUE];
}

【讨论】:

  • 我添加了一个点击手势识别器来关闭键盘,但现在用户无法点击表格视图的任何内容
  • @MbusiHlatshwayo 您是否将cancelsTouchesInView 设置为FALSE
【解决方案2】:

如果您的背景是 UIView,您可以在身份检查器中将其更改为 UIControl,并将其发送到让第一响应者辞职的操作。

由于您的背景是 UITableView,您应该将 rightBarButtonItem 添加到您的导航栏,例如“取消”或“完成”,并将其发送到一个让第一响应者辞职的方法*。

*您的第一响应者是用户正在输入的字段。

[textField resignFirstResponder];

斯威夫特:

textField.resignFirstResponder();

【讨论】:

    【解决方案3】:

    你可以试试这个代码:

    func textFieldShouldReturn(textField: UITextField) -> Bool{
        textField.resignFirstResponder()
        return true
    }
    

    当按下键盘上的“返回”按钮时,这将关闭键盘。

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2013-01-05
      • 2011-10-17
      • 1970-01-01
      • 2012-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-12
      • 1970-01-01
      相关资源
      最近更新 更多