2 xinyoulingxi1 tong xinyoulingxi1_tong 于 2012.12.06 13:36 提问

UIButton-编程创建问题

编程创建了UIButton:

- (void)viewDidLoad
{
    [paymentsHomeView setFrame:CGRectMake(0, 0, 320, 520)]; // paymentsHomeView is added and referenced in IB

    UIButton *paymentButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 45, 300, 41)];
    paymentButton.titleLabel.text = @"Button";
    paymentButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [paymentButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.paymentsHomeView addSubview:paymentButton];

    [super viewDidLoad];
}

-(void) buttonClicked {

    NSLog(@"buttonClicked");
}

什么也没输出,Button没创建成功。

但是同样方法创建UITextField就成功了。

谢谢,请指点

2个回答

redCoral_
redCoral_   2012.12.06 14:15
已采纳

在初始化语句之后要给Button设置框架,用不同方式命名Button。

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self 
           action:@selector(buttonClicked:)
 forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Button" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[self.view addSubview:button];
xinyoulingxi1_tong
xinyoulingxi1_tong 厉害
5 年多之前 回复
abcdeFGh_xyz
abcdeFGh_xyz   2012.12.06 14:06

你在这创建Button:

UIButton *paymentButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 45, 300, 41)];

然后又创建了一个,新的Button会覆盖前一个,所以设置要重构框架:

paymentButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];

所以我建议:

paymentButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[paymentButton setFrame:CGRectMake(10, 45, 300, 41)];

    paymentButton.titleLabel.text = @"Button";
    [paymentButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.paymentsHomeView addSubview:paymentButton];
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!