直接使用 alloc/initWithFrame: 再呼叫 buttonWithType: 會導致按鈕實例被覆蓋,造成框架與標題設定失效。正確流程應先決定按鈕類型,再設定屬性。
UIButton *paymentButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 45, 300, 41)];
paymentButton.titleLabel.text = @"Button"; // 無效
paymentButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; // 覆蓋前一個實例
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:@"Button" forState:UIControlStateNormal]; // 必須用 setTitle:forState:
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0); // 設定框架
[button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
buttonWithType: 建立按鈕,確保類型正確(系統風格、自訂等)。setTitle:forState: 設定,直接存取 titleLabel.text 不會生效。UIControlEventTouchUpInside 為標準點擊事件。