控制器通信的目标 C 视图 [英] Objective C View to Controller Communication
问题描述
在视图中接受用户输入然后将其传输到该视图的控制器的正确方法是什么?我知道 NotificationCenter 是一种选择,但肯定有一种更优雅的方式将数据从视图传输到其控制器吗?
What is the proper way to accept user input in a view and then transfer it to that view's controller? I know the NotificationCenter is one option, but surely there is a more elegant way to transfer data from a view to its controller?
非常感谢所有帮助,我总是接受答案!
All help is greatly appreciated and I always accept an answer!
推荐答案
您正在寻找 Delegation
或 Data Source
.您可以在此处查看更多信息,Delegation和数据源
You're looking for Delegation
or a Data Source
. You can see more information about this here, Delegation and Data Sources
这方面的一个简短示例是:
A brief example of this would be, something along the lines of this:
//MyViewSubclass.h
@protocol MyViewSubclassDelegate
//Implement your delegate methods here.
-(void)didTouchView;
@end
@interface MyViewSubclass {
id<MyViewSubclassDelegate>delegate;
}
@property(nonatomic,assign)id<MyViewSubclassDelegate>delegate;
当然,@synthesize
你在MyViewSubclass.m
现在在类的标题中,您希望 MyViewSubclass
的委托成为,您需要符合 `MyViewSubclassDelegate 协议.
Now in the class's header, that you want the delegate of MyViewSubclass
to be, you need to conform to the `MyViewSubclassDelegate Protocol.
#import "MyViewSubclass.h"
@interface MyViewController : UIViewController <MyViewSubclassDelegate>
在MyViewController.
的@implementation
中,实现-(void)didTouchView
的MyViewSubclassDelegate
方法.
当您初始化并创建您的 MyViewSubclass
对象时,您将 MyViewController
设置为委托:
When you initialize and create your MyViewSubclass
object, you set MyViewController
as the delegate:
myViewSubclass.delegate = self // Self being MyViewController.
在你的 MyViewSubclass
中,当你准备好转发任何信息,或者只是想触发一个你会做的方法时 [self.delegate didTouchView]
In your MyViewSubclass
, when you're ready to forward any information, or simply want to fire a method you would do [self.delegate didTouchView]
希望这有帮助!
这篇关于控制器通信的目标 C 视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!