簡體   English   中英

iOS:UIButton不顯示

[英]iOS: UIButton doesn't show up

我正在創建一個簡單的按鈕,並將其作為子視圖添加到主視圖。 它沒有出現。

這是設置代碼:

UIButton* contactButton = [[UIButton alloc] init];
contactButton.titleLabel.text = @"Contact Developer";
[contactButton sizeToFit];
[self.view addSubview:contactButton];
NSLog(@"X: %f || Y: %f || Width: %f || Height: %f", contactButton.frame.origin.x, contactButton.frame.origin.y, contactButton.frame.size.width, contactButton.frame.size.height);

您可能已經注意到,我在最后放置了一些調試代碼,以查看按鈕的位置和尺寸。 它們是:X:0,Y:0,寬度:30,高度:34

這意味着它應該顯示在左上角,但不是。 怎么了?

您應該使用以下方法初始化按鈕:

UIButton* contactButton = [UIButton buttonWithType:UIButtonTypeCustom];

嘗試以其他方式構造按鈕:

UIButton* contactButton = [UIButton buttonWithType:UIButtonTypeCustom];
contactButton.backgroundColor = [UIColor redColor];
contactButton.titleLabel.text = @"Contact Developer";
[contactButton sizeToFit];
[self.view addSubview:contactButton];

一種可能的原因是您直接使用了titleLabel 考慮改用setTitle:forState:方法。

可以肯定的是,請考慮將backgroundColor設置為調試步驟,以確保它出現了。


編輯其他建議,請嘗試使用buttonWithType:而不是[[UIButton alloc] init] 我建議使用UIButtonTypeSystem而不是UIButtonTypeCustom

您確定按鈕沒有顯示嗎?

我認為您未正確設置按鈕的標題,並且由於默認UIButton具有清晰的背景和白色標題,因此如果您的超級視圖也為白色,則該按鈕不可見。
而不是設置:
contactButton.titleLabel.text = @"Contact Developer"
采用:
[contactButton setTitle:@"Contact Developer" forState:UIControlStateNormal]

但是,您可以首先嘗試將按鈕的backgroundColor設置為與超級視圖不同的按鈕,以查看是否添加了該按鈕。

希望能幫助到你!
(對不起,如果我輸入錯誤,我的英語)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM