【问题标题】:Detect when stopped typing in UITextField检测何时停止在 UITextField 中输入
【发布时间】:2015-09-22 11:46:28
【问题描述】:

我应该如何检测UITextField 中的输入是否停止?我应该使用某种UITextFieldTextDidEndEditingNotification 函数吗?我试图创建一个类似搜索的 instagram,它会在不输入一秒钟后显示结果。

【问题讨论】:

标签: ios objective-c uitextfield


【解决方案1】:

试试这个代码:

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSDate* timeStamp = [NSDate date];
    _timeStamp = timeStamp;
    CGFloat END_TYPING_TIME = 1.5;
    [self performSelector:@selector(endTyping:) withObject:timeStamp afterDelay:END_TYPING_TIME];
    return YES;
}

-(void) endTyping:(NSDate*) timeStamp {
    if ([timeStamp isEqualToDate:_timeStamp]) { //if it is the last typing...
        //TODO: do what ever you want to do at the end of typing...
    }
}

根据您的情况确定 END_TYPING_TIME 是什么...

_timeStampNSDate 类型的字段。

【讨论】:

  • 使用 NSTimer 怎么样?
  • 什么不起作用?它没有到达'endTyping:'?它不进入'if'语句?它没有到达委托函数(您是否分配了 textField 的委托字段)?
  • @Yedidya 它没有到达 endTyping 函数
【解决方案2】:

此方法使用 NSTimer 在文本字段更改后 1 秒安排搜索。如果在该秒结束之前输入了一个新字符,则计时器重新开始。这样,搜索只会在最后一次更改后触发。

首先,确保 ViewController 符合 UITextFieldDelegate 协议:

//
//  ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITextFieldDelegate>

@end

然后,实现定时搜索:

//
//  ViewController.m

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *textfield;
@property (strong, nonatomic) NSTimer * searchTimer;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // declare this view controller as the delegate
    self.textfield.delegate = self;

    // handle the change event (UIControlEventEditingChanged) by calling (textFieldDidChange:)
    [self.textfield addTarget:self
                  action:@selector(textFieldDidChange:)
        forControlEvents:UIControlEventEditingChanged];

}

// reset the search timer whenever the text field changes
-(void)textFieldDidChange :(UITextField *)textField{

    // if a timer is already active, prevent it from firing
    if (self.searchTimer != nil) {
        [self.searchTimer invalidate];
        self.searchTimer = nil;
    }

    // reschedule the search: in 1.0 second, call the searchForKeyword: method on the new textfield content
    self.searchTimer = [NSTimer scheduledTimerWithTimeInterval: 1.0
                                                        target: self
                                                      selector: @selector(searchForKeyword:)
                                                      userInfo: self.textfield.text
                                                       repeats: NO];

}


- (void) searchForKeyword:(NSTimer *)timer
{
    // retrieve the keyword from user info
    NSString *keyword = (NSString*)timer.userInfo;

    // perform your search (stubbed here using NSLog)
    NSLog(@"Searching for keyword %@", keyword);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

【讨论】:

    【解决方案3】:

    我就是这样做的,它在 Swift 3

    中对我有用
    import UIKit
    
    // don't forget to add UITextFieldDelegate
    class ViewController: UIViewController, UITextFieldDelegate {
    
        @IBOutlet var textField: UITextField!
    
        var searchTimer: Timer?
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // declare textField as delegate
            self.textField.delegate = self
    
            // handle the editingChanged event by calling (textFieldDidEditingChanged(-:))
            self.textField.addTarget(self, action: #selector(textFieldDidEditingChanged(_:)), for: .editingChanged)
        }
    
        // reset the searchTimer whenever the textField is editingChanged
        func textFieldDidEditingChanged(_ textField: UITextField) {
    
            // if a timer is already active, prevent it from firing
            if searchTimer != nil {
                searchTimer?.invalidate()
                searchTimer = nil
            }
    
            // reschedule the search: in 1.0 second, call the searchForKeyword method on the new textfield content
            searchTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(searchForKeyword(_:)), userInfo: textField.text!, repeats: false)
        }
    
        func searchForKeyword(_ timer: Timer) {
    
            // retrieve the keyword from user info
            let keyword = timer.userInfo!
    
            print("Searching for keyword \(keyword)")
        }
    
    }
    

    【讨论】:

    • 这正是我想要的
    【解决方案4】:

    迅速
    xcode - 10

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange,
                   replacementString string: String) -> Bool {
        NSObject.cancelPreviousPerformRequests(
            withTarget: self,
            selector: #selector(self.getHintsFromTextField),
            object: textField)
        self.perform(
            #selector(self.getHintsFromTextField),
            with: textField,
            afterDelay: 0.5)
        return true
    }
    
    @objc func getHintsFromTextField(textField: UITextField) {
        print("Hints for textField: \(textField)")
    }
    
    

    【讨论】:

    • 完美解决方案
    • 这就是答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-27
    • 2015-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多