iphone - 在 Objective C 中获取第一响应者

标签 iphone objective-c cocoa-touch macos cocoa

我无法确定哪个 UITextField 是当前的 First Responder。

我想做的是在用户点击特定的 UITextField 时设置一个 bool 值。因此,要做到这一点,我需要能够判断这个特定的文本字段是否已成为第一响应者。

我知道如何设置第一响应者,但不确定如何判断一个字段是否真的成为第一响应者。

最佳答案

[...] but just not sure how to tell if a field has actually become the first responder.

UIViewUIResponder 继承了 isFirstResponder 方法,它告诉您这一点。

无需检查各个控件/ View 并且无需针对所有可能的第一响应者的不同类型的多种方法即可找到第一响应者的最简单方法是在 UIView 上创建一个类别,其中添加findFirstResponder 方法:

UIView+FirstResponder.h

#import <UIKit/UIKit.h>

@interface UIView (FirstResponder)
- (UIView *)findFirstResponder;
@end

UIView+FirstResponder.m

#import "UIView+FirstResponder.h"

@implementation UIView (FirstResponder)

- (UIView *)findFirstResponder
{
    if ([self isFirstResponder])
        return self;

    for (UIView * subView in self.subviews) 
    {
        UIView * fr = [subView findFirstResponder];
        if (fr != nil)
            return fr;
    }

    return nil;
}

@end

关于iphone - 在 Objective C 中获取第一响应者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8772468/

相关文章:

iphone - 根据内容更改单个 UITableViewCell 的外观

objective-c - 从另一个应用程序接收文本

cocoa-touch - RFC 3339 日期字符串的 NSDateFormatter 格式字符串,不带毫秒

ios - 不同方向的不同自动布局约束集

iphone - Objective C iPhone 子类化 UITextField catch 值已更改

iphone - iPhone 上的 OpenGL ES 不绘制任何东西

objective-c - 如何在 UICollectionViewLayout 和 UIViewController 之间传递数据

iphone - UIWebView 泄漏?有人可以确认吗?

iphone - ObjC++ 中的私有(private)方法

iphone - 从 UIImagePickerController 抓取视频的第一帧?