如何在点击UI按钮时将值发送到函数

问题描述:

NSString *name = @"John"; 

我需要通过上面的变量值,当点击uibutton。目前,我创建了UIButton的象下面这样:如何在点击UI按钮时将值发送到函数

sendButton = [[UIButton alloc] initWithFrame:CGRectMake(170, 350, 90, 30)]; 

[sendButton setTitle:@"YES!" forState:UIControlStateNormal]; 

[sendButton addTarget:self action:@selector(sendAlert forControlEvents:UIControlEventTouchUpInside]; 

[sendButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; 

sendButton.backgroundColor = [UIColor whiteColor]; 

[popoverView addSubview:sendButton]; 

[sendButton release]; 

当我点击上面的按钮,它会调用该方法,但我想通过变量(名称)的功能...

请指引我得到它....

您可以创建自定义按钮的UIButton 的子类,比如,你可以创建为

性能

在.h文件中

@interface CustomButton : UIButton 
{ 
    NSString *name; 

} 

@property (nonatomic,retain) NSString *name; 
@end 

.m文件

@implementation CustomButton 

@synthesize name; 

- (void)dealloc{ 

    [name release]; 

    [super dealloc]; 
} 

@end 

现在你在哪里,其中被触发,你可以使用访问它的方法创建按钮

sendButton = [[CustomButton alloc] initWithFrame:CGRectMake(170, 350, 90, 30)]; 

[sendButton setTitle:@"YES!" forState:UIControlStateNormal]; 

[sendButton setName:@"John"]; 

[sendButton addTarget:self action:@selector(sendAlert forControlEvents:UIControlEventTouchUpInside]; 

[sendButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; 

sendButton.backgroundColor = [UIColor whiteColor]; 

[popoverView addSubview:sendButton]; 

[sendButton release]; 

现在的代码按钮的属性名为

+0

Hi..Thnks您time..is这将参数传递给函数 – iPhonegal 2010-10-29 13:23:58

虽然你可以继承UIButton并添加属性es等等,等等,你最好在popoverView类中命名一个实例变量。 sendAlert方法也可以访问它。每次需要将数据传递给它们时,您都不希望子类化控件。

Sherry的答案在技术上是正确的,但是,林不知道它是否是一个潜在的设计模式问题的解决方案。

变量'name'会改变吗?如果是这样,它是如何改变(领域,列表选择..等)?

如果它dosnt改变那么你应该#define它,如果它确实改变(用户输入),那么你的事件应该看数据源,UI字段或实例变量。

你不需要继承UIButton。

将一个NSString属性添加到popoverView的类(您正在关注MVC吗?popoverView应该是一个控制器)。然后在将其添加到子视图之前,将第一个对象中的NSString分配给popoverView中的NSString。完成了!

您也可以考虑使用通知,如果你要在别的地方在你的应用程序中使用该名称。

如果您发布整个代码,我会修复代码为你:)

+0

一个唯一的办法是不明确以及如果你有多个按钮需要这样做呢? – user102008 2011-04-23 01:39:16