在代码中将UIButton连接到IBOutlet和IBAction

时间:2013-08-26 08:03:01

标签: ios uibutton ibaction iboutlet

我有这是viewDidLoad:

// Set up register button
UIButton *registerButton = [UIButton buttonWithType:UIButtonTypeSystem];
[registerButton setTitle:@"Register" forState:UIControlStateNormal];
registerButton.frame = CGRectMake(0.0, 0.0, self.screenWidth / 2.0, 100.0);

和此:

- (IBAction)buttonPressed:(UIButton *)sender
{
}

我的.h文件中也有这个:

@property (nonatomic, weak) IBOutlet UIButton *registerButton;

如何将IBOutlets和IBActions连接到我在代码中创建的按钮?

2 个答案:

答案 0 :(得分:2)

您必须将目标设置为按钮,如下所示:

[registerButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];

答案 1 :(得分:0)

UIButton *registerButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            registerButton.frame=CGRectMake(150, 10, 150,25);
            registerButton.userInteractionEnabled = YES;

            [registerButton setTitle:@"Register" forState:UIControlStateNormal];

            [registerButton addTarget:self action:@selector(buttonPressed:) 
               forControlEvents:UIControlEventTouchUpInside];
            [view.contentView addSubview:registerButton];

试试这个。我认为这对你有用。