programing

UITableView 스크롤 시 키보드 숨기기

cafebook 2023. 7. 2. 20:58
반응형

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 {
...

저는 이 수업을 이렇게 사용합니다.하지만 위임 기능 my.UI 테이블 보기ViewController에서 TouchsBegin이 작동하지 않습니다.

.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];
}

이 구현과 관련하여 몇 가지 문제가 있습니다.
myUITableViewView Controller에서 Touchs가 작동하지 않습니다.
MyUITableView.m의 NSLog - NSLog(@"대리인 myUI 테이블 보기Touchs Begin"; 테이블을 터치할 때만 작동합니다.스크롤을 시작할 때도 어떻게 작동하게 되었습니까?
scrollViewDidScroll을 재정의하려고 하지만 comiler가 MyUITable이라고 말했습니다.이 문자열 [superscrollViewDidScroll:scrollView]에서 View가 응답하지 않을 수 있습니다.

iOS 7.0 이상에서 이를 달성하는 가장 깨끗한 방법은 다음과 같습니다.

tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;

또는 터치 시 대화식으로 해제하기

tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;

또는 Swift에서:

tableView.keyboardDismissMode = .onDrag

대화형으로 해제하기

tableView.keyboardDismissMode = .interactive

이를 위해 UITableView를 하위 분류해야 하는 이유를 잘 모르겠습니다.

일반 UITableView가 포함된 보기 컨트롤러에서 다음을 추가해 보십시오.

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

이 작업은 인터페이스 빌더에서 수행할 수 있습니다.다음 항목을 선택UITableView속성 검사기를 엽니다.스크롤 보기 섹션에서 키보드 필드를 끌 때 해제로 설정합니다.

enter image description here

위의 답변에 업데이트를 추가하기 위해서입니다.아래는 Swift 1.2에서 작동했습니다.

tableView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag

또는

tableView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.Interactive

스위프트 5와 함께

표 보기를 스크롤할 때 키보드를 숨기고 편집을 제대로 중지하려면 다음 두 가지 유형의 대답을 결합해야 합니다.

  1. IB에서 키보드 해제 모드를 설정합니다(Kyle 설명대로).ViewDidLoad()예를 들어, 코드(페이가 설명한 대로):
tableView.keyboardDismissMode = .onDrag
  1. 현재 텍스트 필드를 첫 번째 응답자로 강제로 사임합니다(Vasily의 응답에서와 같이).우리는 단지 다음 사항을 우리의 것에 추가하면 됩니다.UITableViewController학급
    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if !tableView.isDecelerating {
            view.endEditing(true)
        }
    }

작업

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>

결과

enter image description here

컨트롤러에 코드를 한 줄도 기록하지 않고 솔루션 작동:

질문은 한 가지 조건(스크롤의 경우)으로만 키보드 숨기기를 처리하는 것입니다.하지만 여기서 저는 텍스트 필드와 키보드를 함께 처리할 수 있는 하나의 솔루션을 추천합니다. 이 솔루션은 UIViewController, UITableView 및 UIScrollView에 매력적으로 작동합니다.흥미로운 사실은 코드를 한 줄도 작성할 필요가 없다는 것입니다.

여기 있습니다: TP KeyboardAvoiding - 키보드와 스크롤을 다룰있는 멋진 솔루션입니다.

iOS 7 이후에는 Tableview 속성을 간단하게 사용할 수 있습니다.

스위프트 3.0+

myTableView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag

목표 C

myTableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;

이전 버전의 경우 스크롤 뷰 대리자를 구현할 수 있습니다.

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

언급URL : https://stackoverflow.com/questions/4399357/hide-keyboard-when-scroll-uitableview

반응형