Mac开发云集iOS之MAC端开发Mac OSX开发

Mac开发之NSTextField添加文字监控

2018-05-28  本文已影响11人  隐身人

新做Mac开发的时候 发现 里面控件和iOS开发是有所区别的,NSTextField 相较于iOS UITextField 里面竟然连最基本的文本监控都没有!!!这在使用当中是万万满足不了用户大大的需求,所以这边仿UITextField 添加 delegate ,监控文字变动方法。具体思路,实现,demo如下:
主要思路是 :使用 NSNotificationCenter 监控 NSTextField 变动 取得具体变动文字值。

自定义NSTextField = MyNSTextField
MyNSTextField.h 代码:

#import <Cocoa/Cocoa.h>

@class MyNSTextField;

@protocol NSTextFieldNotifyingDelegate <NSTextFieldDelegate>

@optional

-(void)textFieldDidChange:(NSTextField *_Nullable)textField;

@end

@interface MyNSTextField : NSTextField

@property (nullable, weak) id<NSTextFieldNotifyingDelegate> delegate;

@end


MyNSTextField.m 代码:

#import "MyNSTextField.h"

@implementation MyNSTextField

@synthesize delegate;

-(id)init{
    self = [super init];
    if(self){
        [self registerForNotifications];
    }
    return self;
}

-(id)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if(self){
        [self registerForNotifications];
    }
    return self;
}

-(id)initWithFrame:(NSRect)frameRect{
    self = [super initWithFrame:frameRect];
    if(self){
        [self registerForNotifications];
    }
    return self;
}

-(void)registerForNotifications{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChange:) name:NSControlTextDidChangeNotification object:self];
}



-(void)textFieldDidChange:(NSNotification *)notification{
    [self.delegate textFieldDidChange:self];
}

@end

使用 VC.m 中 :

#import "ViewController.h"
#import "MyNSTextField.h"
@interface ViewController ()<NSTextFieldNotifyingDelegate>
{
    
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // Do any additional setup after loading the view.
    
    MyNSTextField *testTF = [[MyNSTextField alloc]init];
    testTF.delegate = self;
    testTF.frame = NSMakeRect( 300 ,100, 100, 100);
    testTF.stringValue = @"我是默认文字";
    [self.view addSubview:testTF];
    
    
}

-(void)textFieldDidChange:(NSTextField *)textField
{
    NSLog(@"textField === %@",textField.stringValue);
}

@end

上一篇 下一篇

猜你喜欢

热点阅读