ios - Android的 "Toast"在iOS的: adding button to message

标签 ios xcode uibutton toast unrecognized-selector

我为在屏幕底部显示消息栏的 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/

相关文章:

ios - UITableViewCell 子类导致无法识别的选择器发送问题

c++ - 如何在静态库中的单独 cpp 文件中链接未引用的变量?

ios - Libgdx IOS 不工作?

iphone - 从 UIButton 创建一个 Popover View ,该 View 显示一个 TableView,其中包含应用内购买项目的列表

ios - UITableView 内的自定义 UIButton 在按下后保持突出显示

ios - 将自定义 UIButton 样式应用于所有按钮

ios - 校准 UI 加速度计?

ios - 如何使用 NSCoding 对通过委托(delegate)传递的值进行编码

ios - 在 Swift 中添加双击手势来编辑和结束编辑

ios - 将闭包保存为变量理解