首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS 程式碼建立 UIButton 失敗:正確初始化與設置框架的步驟

     編輯:程式設計綜合問答

直接使用 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 為標準點擊事件。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved