我为在屏幕底部显示消息栏的 ToastView(类似于 Android 的 toast)创建了一个 iOS 类。我在 ToastView 中添加了一个按钮,并解决了我原来的错误。触摸按钮的 NSLog 显示在控制台中,但我需要在单击按钮时将 BOOL 值发送回 HomeViewController,我不确定如何使用此按钮在两者之间进行通信。有帮助吗?
在 ToastView.h 中:
+ (void)showToastInParentView: (UIView *)parentView withText:(NSString *)text withDuaration:(float)duration;
+ (void)undoButtonClicked:(id)sender;
在 ToastView.m 中:
//shows the "toast" message
+ (void)showToastInParentView: (UIView *)parentView withText:(NSString *)text withDuaration:(float)duration {
//code to show message
UIButton *undoButton = [[UIButton alloc] initWithFrame:CGRectMake(toast.frame.size.width - 60.0, toast.frame.size.height - 35.0, 40, 20)];
undoButton.backgroundColor = [UIColor lightGrayColor];
[undoButton addTarget:self action:@selector(undoButtonClicked:) forControlEvents:UIControlEventTouchDown];
}
+(void) undoButtonClicked:(id)sender {
NSLog(@"UNDO BUTTON TOUCHED");
}
然后我在 HomeViewController 中使用以下代码调用 ToastView:
[ToastView showToastInParentView:self.view withText:@"TOAST MESSAGE!" withDuaration:5.0];
最佳答案
看到您更新后的代码,问题出在 undoButtonClicked:
方法,在您的情况下它是一个类方法(以“+”为前缀)。
您想通过将前缀更改为“-”使其成为对象方法。这样,该类就知道要在该类的实例化对象上调用它。当您使用 addTarget:action:forControlEvents:
时,该操作是您的目标选择器。
作为苹果says :
A selector is the name used to select a method to execute for an object
所以它需要是一个对象方法,而不是类方法。
您的代码应如下所示:
.h:
+ (void)showToastInParentView: (UIView *)parentView withText:(NSString *)text withDuaration:(float)duration;
- (void)undoButtonClicked:(id)sender;
.m:
//shows the "toast" message
+ (void)showToastInParentView: (UIView *)parentView withText:(NSString *)text withDuaration:(float)duration {
//code to show message
UIButton *undoButton = [[UIButton alloc] initWithFrame:CGRectMake(toast.frame.size.width - 60.0, toast.frame.size.height - 35.0, 40, 20)];
undoButton.backgroundColor = [UIColor lightGrayColor];
[undoButton addTarget:self action:@selector(undoButtonClicked:) forControlEvents:UIControlEventTouchDown];
}
-(void) undoButtonClicked:(id)sender {
NSLog(@"UNDO BUTTON TOUCHED");
}
关于ios - Android的 "Toast"在iOS的: adding button to message,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26282619/