【问题标题】:Assigning a variable from another class从另一个类分配变量
【发布时间】:2015-08-30 15:36:45
【问题描述】:

我有一个 UIView 和一个 UIButton 在 1 个类中创建:“viewClass”。在我的@ class @ class中,我叫viewClas和我需要在mainVc 987654327选中mainVc时,所以我创建了一个protocol。 (我希望这很清楚。)

这是我设置protocoldelegate 的方法:

viewClass.h

@protocol ViewClassDelegate

-(void)buttonWasClicked;

@end

...
@property (nonatomic, strong) id<ViewClassDelegate> delegate;

viewClass.m

[submitButton addTarget:self action:@selector(submitButtonTapped) forControlEvents: UIControlEventTouchUpInside];

- (void)submitButtonTapped {
    [self.delegate buttonWasClicked];
}

mainVC.m

// Imported and called the delegate in mainVC.h. Then in .m I set the delegate

-(void)buttonWasClicked {
    // Perform some action
}

有没有办法将NSString 传递给buttonWasClicked?我不是这个意思:

- (void)buttonWasClicked:(NSString *)myString

因为myString 没有价值,除非我在mainVC 方法中分配它。我想将它分配给submitButtonTapped(在myView.m)。

基本上,我想要这样的东西:

- (void)textFieldDidBeginEditing:(UITextField *)textField

在该方法中,它知道textField 是什么,而无需我在使用该方法时对其进行定义。

希望这很清楚。如果有人可以更好地解释它,请随时编辑它。如果您需要更多说明,请在 cmets 中询问。

【问题讨论】:

  • 你想从哪里传递NSString到哪里?
  • myViewmainVC ?
  • 是的。通过buttonWasClicked方法从myViewmainVC

标签: ios objective-c methods protocols


【解决方案1】:

我不确定这是不是你想要的:

@protocol ViewClassDelegate

-(void)buttonWasClicked:(NSString*)value;

@end

...
@property (nonatomic, weak) id<ViewClassDelegate> delegate;

[submitButton addTarget:self action:@selector(submitButtonTapped:) forControlEvents: UIControlEventTouchUpInside];

- (void)submitButtonTapped:(UIButton*)sender {
    [self.delegate buttonWasClicked:stringToSendWhereverHasBeenDefined];
}

...

-(void)buttonWasClicked:(NSString*)value {
    // Perform some action
}

【讨论】:

  • 我想传递一个已经定义的字符串而不是按钮
  • 我已经编辑了答案。如果我遗漏任何细节,请告诉我
【解决方案2】:

viewClass.h

@protocol ViewClassDelegate

-(void)buttonWasClicked:(NSString *)aString;

@end

viewClass.m

[submitButton addTarget:self action:@selector(submitButtonTapped) forControlEvents: UIControlEventTouchUpInside];

- (void)submitButtonTapped {
    [self.delegate buttonWasClicked:@"this is a string"];
}

ma​​inVC.m

// Imported and called the delegate in mainVC.h. Then in .m I set the delegate

-(void)buttonWasClicked:(NSString *)aString {
    // aString = this is a string 
}

【讨论】:

  • 哇!!不敢相信这么容易!!谢谢!!那有名字吗?
  • :) 不确定是否有任何特殊条款。但这只是委托。
猜你喜欢
  • 2018-03-17
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多