如何将一个方法与这个按钮关联起来?

发布于 2024-09-27 09:52:17 字数 650 浏览 1 评论 0原文

我有一个显示图像和文本的导航栏按钮。这是代码:

UIImage *saveImage = [UIImage imageNamed:@"star.png"];

UIButton *saveButton = [UIButton buttonWithType:UIButtonTypeCustom];

[saveButton setBackgroundImage:saveImage forState:UIControlStateNormal];
[saveButton setTitle:@"Save" forState:UIControlStateNormal];

saveButton.frame = (CGRect) {
    .size.width = 100,
    .size.height = 30,
};

UIBarButtonItem *barButton= [[UIBarButtonItem alloc] initWithCustomView:saveButton];

[self.navigationItem setRightBarButtonItem:barButton animated:YES];

我尝试过

[barButton setAction:@selector(saveArray)];

,但不起作用。

I have a navigation bar button that displays both image and text. This is the code:

UIImage *saveImage = [UIImage imageNamed:@"star.png"];

UIButton *saveButton = [UIButton buttonWithType:UIButtonTypeCustom];

[saveButton setBackgroundImage:saveImage forState:UIControlStateNormal];
[saveButton setTitle:@"Save" forState:UIControlStateNormal];

saveButton.frame = (CGRect) {
    .size.width = 100,
    .size.height = 30,
};

UIBarButtonItem *barButton= [[UIBarButtonItem alloc] initWithCustomView:saveButton];

[self.navigationItem setRightBarButtonItem:barButton animated:YES];

I tried this

[barButton setAction:@selector(saveArray)];

but it doesn't work.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

柠檬心 2024-10-04 09:52:17

请记住,您还必须指定目标。您可以将操作/目标设置为 UIButton 对象本身:

[saveButton addTarget:target action:@selector(saveArray) forControlEvents:UIControlEventTouchUpInside];

我尝试直接将目标/操作设置为 UIBarButtonItem,但由于某种原因,在 UIButton 用于自定义视图的情况下似乎不起作用。

Remember that you must specify target as well. You can set action/target to the UIButton object itself:

[saveButton addTarget:target action:@selector(saveArray) forControlEvents:UIControlEventTouchUpInside];

I've tried to set target/action to the UIBarButtonItem directly but it seems not to work in case of UIButton for custom view for some reason.

吃兔兔 2024-10-04 09:52:17

你记得设定目标吗?如果所需的方法属于同一个类,您可以这样做:

[barButton setTarget:self];

也就是说,actiontarget 都是属性(Obj-C 2.0 的新功能),请考虑使用点符号:

barButton.action = @selector(saveArray:)
barButton.target = self;

Did you remember to set the target? If the desired method belongs to the same class, you could do:

[barButton setTarget:self];

That said, action and target are both properties (new to Obj-C 2.0), consider using the dot notation:

barButton.action = @selector(saveArray:)
barButton.target = self;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文