2015-10-03 327 views
0

當我嘗試發佈以下代碼時,我的應用程序只顯示按鈕文本應該在的空矩形。我是xcode的初學者,我從其他教程中確定了這些代碼。不顯示按鈕文本

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    UILabel *player1 = [[UILabel alloc]initWithFrame:CGRectMake(35, 120,130, 30)]; 
    [player1 setText:@"Player"]; 
    player1.layer.borderWidth = 1.0; 
    player1.layer.borderColor = [UIColor blackColor].CGColor; 
    player1.textAlignment = UITextAlignmentCenter; 
    [self.view addSubview: player1]; 

    UIButton *score1 = [[UIButton alloc]initWithFrame:CGRectMake(165, 120, 60, 30)]; 
    [score1 setTitle:@"0" forState:UIControlStateNormal]; 
    score1.layer.borderWidth = 1.0; 
    score1.layer.borderColor = [UIColor blackColor].CGColor; 
    [self.view addSubview: score1]; 


    UILabel *player2 = [[UILabel alloc]initWithFrame:CGRectMake(35, 150, 130, 30)]; 
    [player2 setText:@"Opponent"]; 
    player2.layer.borderWidth = 1.0; 
    player2.layer.borderColor = [UIColor blackColor].CGColor; 
    player2.textAlignment = UITextAlignmentCenter; 
    [self.view addSubview: player2]; 
} 

就像我說的,除了按鈕中的文字都顯示出來。

+0

有人在這裏有相同的問題:http://stackoverflow.com/questions/10748238/in-ios-can-a-uibutton-be-added-by-alloc-and-initwithframe – WangYudong

回答

3

之所以按鈕看起來是空白的,因爲它的文本顏色爲白色實際。只要給它一個不同的顏色和0現在將顯示:

score1.layer.backgroundColor = [UIColor blackColor].CGColor; 

enter image description here

如果你不想改變按鈕的背景顏色,你可能要設置文本顏色:

[score1 setTitleColor:[UIColor blueColor] forState:UIControlStateNormal]; 

閱讀Question: [initWithFrame:frame] vs. [UIButton buttonWithType],瞭解更多關於使用這些不同方法創建UIButton的信息。

+0

非常好,但用'buttonWithType:'創建按鈕更好。這就是它的目的。 :) – matt

+0

@matt我認爲是的。 – WangYudong

1

的問題是你在建立按鈕的方式:

UIButton *score1 = [[UIButton alloc]initWithFrame:CGRectMake(165, 120, 60, 30)]; 

那不是你怎麼做。這樣做:

UIButton *score1 = [UIButton buttonWithType:UIButtonTypeSystem]; 
score1.frame = CGRectMake(165, 120, 60, 30); 

一切都會在那之後!

enter image description here

+1

爲什麼'initWithFrame' doesn'在這裏工作? – WangYudong

+0

因爲這不是你怎麼做的。天哪,我想我是這麼說的。 :) @王玉東親自嘗試一下。運行他的代碼。然後將那一行更改爲我的代碼。你會看到不同之處! – matt