【问题标题】:How to make two Classes delegate of UITextView?如何使 UITextView 的两个类代表?
【发布时间】:2016-07-04 08:27:08
【问题描述】:

我有一个 textView“TexV”,它有一个从 UITextView 继承的自定义类“TexV_Class”,我有一个 viewController“VC”,它有一个名为“VC_Class”的自定义类

现在我怎样才能让两个类“TexV_Class”和“VC_Class”委托并让它们一起工作?是否有可能在两个类中运行相同的委托方法(例如 textViewDidChange)(暂时保留运行顺序)

我虽然让两个类都委托了,但只运行了一个(运行 textView 委托方法的 VC_Class)

【问题讨论】:

  • 如果你真的需要这个(你可能想先重新考虑你的应用程序结构)看看MultiDelegateILABMultiDelegate。使用这些类有一些陷阱,但有据可查。

标签: ios delegates uitextview uitextviewdelegate


【解决方案1】:

你不能。委托机制通过一个回调对象来工作,如果您希望多个项目根据委托做出反应,您可以通过以下两种方式之一解决这个问题:

1- 向您的一位代理人发出通知,以便另一位代理人可以采取相应行动

2- 在 TexV_Class 上设置一个自定义委托,该委托符合 VC_Class 想要采用的 UITextView 的方法,并让 TexV_Class 从它的委托回调中调用此委托。

【讨论】:

    【解决方案2】:

    我建议你 3 种方法来做到这一点:

    1) 使用 NSNotificationCenter(模式帮助 1 个对象通信一对多对象)

    2) 使用多播委托模式。实现细节,可以参考这个http://blog.scottlogic.com/2012/11/19/a-multicast-delegate-pattern-for-ios-controls.html

    3) 使用Proxy 设计模式。 (我选择了这种方式)

    class MyTextView.h
    
    @protocol NJCustomTextViewDelegate <NSObject>
    
    - textViewShouldBeginEditing:
    - textViewDidBeginEditing:
    - textViewShouldEndEditing:
    - textViewDidEndEditing:
    
    @end
    
    @property (nonatomic, weak) id< NJCustomTextViewDelegate >textViewDelegate;
    

    使用这个:

    in MyTextView.m
    
    self.delegate = self;
    
    -  (void)textViewShouldBeginEditing:(UITextView)textView
    {
        // Handle business logi
        // .... Do your logic here
    
        if ([self.textViewDelegate responseToSelector:@selector(textViewShouldBeginEditing:)])
        {
            [self.textViewDelegate textViewShouldBeginEditing:self];
        }
    }
    
    In MyViewController.m
    
    MyTextView textView = ....
    textView.textViewDelegate = self;
    

    【讨论】:

      猜你喜欢
      • 2012-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      相关资源
      最近更新 更多