簡體   English   中英

滾動UITableView時隱藏鍵盤

[英]Hide keyboard when scroll UITableView

在我的應用程序中,當我開始滾動UITableView時,我想隱藏鍵盤。 我在互聯網上搜索這個,大多數答案是子類化UITableView(http://stackoverflow.com/questions/3499810/tapping-a-uiscrollview-to-hide-the-keyboard)。

我做了子類但它不起作用。

#import <UIKit/UIKit.h>

@protocol MyUITableViewDelegate <NSObject>
@optional
- (void)myUITableViewTouchesBegan;
@end

@interface MyUITableView : UITableView <UITableViewDelegate, UIScrollViewDelegate> {
    id<MyUITableViewDelegate> delegate;
}
@end

.m文件

#import "MyUITableView.h"

@implementation MyUITableView

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    NSLog(@"delegate scrollView"); //this is dont'work
    [super scrollViewDidScroll:scrollView];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"delegate myUITableViewTouchesBegan"); // work only here
    [delegate myUITableViewTouchesBegan];
    [super touchesBegan:touches withEvent:event];

}

- (void)dealloc {
...

我像這樣使用這個類。 但委托函數myUITableViewTouchesBegan在ViewController中不起作用

。H

#import <UIKit/UIKit.h>
#import "MyUITableView.h"

@interface FirstViewController : UIViewController <UITableViewDelegate, UISearchBarDelegate, MyUITableViewDelegate> {
    MyUITableView *myTableView;
    UISearchBar *searchBar; 
}

@property(nonatomic,retain) IBOutlet MyUITableView *myTableView;
...

.M

- (void) myUITableViewTouchesBegan{
    NSLog(@"myUITableViewTouchesBegan");
    [searchBar resignFirstResponder];
}

我對這個實現有一些麻煩:
1)myUITableViewTouchesBegan在ViewController中不起作用
2)來自MyUITableView.m的 - 只有當我觸摸桌子時工作。 當我開始滾動時,它是如何工作的?
我嘗試覆蓋scrollViewDidScroll但是comiler說MyUITableVIew可能不響應這個字符串

以下是在iOS 7.0及更高版本中實現此目的的最簡潔方法:

tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;

或者在觸摸時以交互方式解散:

tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;

或者在Swift中:

tableView.keyboardDismissMode = .onDrag

以交互方式解雇:

tableView.keyboardDismissMode = .interactive

不知道為什么你需要為此子類化UITableView。

在包含普通UITableView的視圖控制器中,嘗試添加以下內容:

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [searchBar resignFirstResponder];
}

您可以在Interface Builder中執行此操作。 選擇您的UITableView並打開Attributes Inspector。 在“滾動視圖”部分中,將“ 鍵盤”字段設置為“拖動時關閉”

在此輸入圖像描述

只是為上面的答案添加更新。 以下在Swift 1.2中為我工作

tableView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag

要么

tableView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.Interactive

無需在Controller中編寫單行代碼即可使用解決方案:

因為你的問題是只用一個條件處理隱藏鍵盤(滾動)。 但是在這里我推薦一種解決方案來處理文本字段和鍵盤,它們就像UIViewController,UITableView和UIScrollView的魅力一樣。 有趣的是,您不需要編寫任何單行代碼。

在這里: TPKeyboardAvoiding - 處理鍵盤和滾動的一個很棒的解決方案

任務

在Swift 3中滾動UITableView時以編程方式隱藏鍵盤

細節

xCode 8.2.1,swift 3

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if !tableView.isDecelerating {
        view.endEditing(true)
    }
}

完整樣本

視圖控制器

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var searchBar: UISearchBar!


    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
        tableView.delegate = self
    }
}

// MARK: - UITableViewDataSource

extension ViewController: UITableViewDataSource {

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 100
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell =  UITableViewCell(style: .subtitle, reuseIdentifier: nil)
        cell.textLabel?.text = "Title"
        cell.detailTextLabel?.text = "\(indexPath)"
        return cell
    }
}

// MARK: - UITableViewDelegate

extension ViewController: UITableViewDelegate {

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if !tableView.isDecelerating {
            view.endEditing(true)
        }
    }
}

故事板

<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="11762" systemVersion="16D32" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
    <device id="retina4_7" orientation="portrait">
        <adaptation id="fullscreen"/>
    </device>
    <dependencies>
        <deployment identifier="iOS"/>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="11757"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <scenes>
        <!--View Controller-->
        <scene sceneID="tne-QT-ifu">
            <objects>
                <viewController id="BYZ-38-t0r" customClass="ViewController" customModule="stackoverflow_4399357" customModuleProvider="target" sceneMemberID="viewController">
                    <layoutGuides>
                        <viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
                        <viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
                    </layoutGuides>
                    <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <subviews>
                            <searchBar contentMode="redraw" translatesAutoresizingMaskIntoConstraints="NO" id="wU1-dV-ueB">
                                <rect key="frame" x="0.0" y="20" width="375" height="44"/>
                                <textInputTraits key="textInputTraits"/>
                            </searchBar>
                            <tableView clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" keyboardDismissMode="interactive" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" translatesAutoresizingMaskIntoConstraints="NO" id="L52-4c-UtT">
                                <rect key="frame" x="0.0" y="64" width="375" height="603"/>
                                <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
                            </tableView>
                        </subviews>
                        <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                        <constraints>
                            <constraint firstItem="wU1-dV-ueB" firstAttribute="bottom" secondItem="L52-4c-UtT" secondAttribute="top" id="0WF-07-qY1"/>
                            <constraint firstAttribute="trailing" secondItem="wU1-dV-ueB" secondAttribute="trailing" id="3Mj-h0-IvO"/>
                            <constraint firstItem="wU1-dV-ueB" firstAttribute="leading" secondItem="L52-4c-UtT" secondAttribute="leading" id="8W5-9j-2Rg"/>
                            <constraint firstItem="wU1-dV-ueB" firstAttribute="trailing" secondItem="L52-4c-UtT" secondAttribute="trailing" id="crK-dR-UYf"/>
                            <constraint firstItem="wU1-dV-ueB" firstAttribute="leading" secondItem="8bC-Xf-vdC" secondAttribute="leading" id="mPe-bp-Dxw"/>
                            <constraint firstItem="L52-4c-UtT" firstAttribute="bottom" secondItem="wfy-db-euE" secondAttribute="top" id="oIo-DI-vLh"/>
                            <constraint firstItem="wU1-dV-ueB" firstAttribute="top" secondItem="y3c-jy-aDJ" secondAttribute="bottom" id="tVC-UR-PA4"/>
                        </constraints>
                    </view>
                    <connections>
                        <outlet property="searchBar" destination="wU1-dV-ueB" id="xJf-bq-4t9"/>
                        <outlet property="tableView" destination="L52-4c-UtT" id="F0T-yb-h5r"/>
                    </connections>
                </viewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="-79.200000000000003" y="137.18140929535232"/>
        </scene>
    </scenes>
</document>

結果

在此輸入圖像描述

在iOS 7之后,您可以簡單地使用tableview屬性

Swift 3.0+

myTableView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag

的ObjectiveC

myTableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;

對於早期版本,實現滾動視圖委托可以工作。

func scrollViewDidScroll(_ scrollView: UIScrollView) {
        view.endEditing(true)
}

使用Swift 5

要在滾動TableView時隱藏鍵盤並停止正確編輯,我們仍需要結合兩種類型的答案:

  1. 設置IB中的鍵盤關閉模式(如Kyle所解釋)或ViewDidLoad()代碼(如Pei所解釋),例如:
tableView.keyboardDismissMode = .onDrag
  1. 強制當前文本字段作為第一響應者辭職(如在Vasily的回答中)。 我們只需要將以下內容添加到UITableViewController類中
    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if !tableView.isDecelerating {
            view.endEditing(true)
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM