2014-01-23 35 views
3

了,我已經建立了我的按鈕,像這樣:的UIButton沒有出現在UIViewController中

CGRect button1Frame = CGRectMake(200, 200, 100, 100); 
self.button1 = [[UIButton alloc] initWithFrame:button1Frame]; 
[self.button1 addTarget:self action:@selector(goToController1:) 
forControlEvents:UIControlEventTouchDown]; 
self.button1.userInteractionEnabled = YES; 
self.button1.opaque = YES; 
self.button1.backgroundColor = [UIColor redColor]; 
[self.button1 setTitle:@"B1" forState:UIControlStateNormal]; 
[self.view addSubview:self.button1]; 

與我的發件人:

- (void) goToController1:(id)sender { 
    NSLog(@"Pressed"); 
} 

和我的視圖控制器已經正確初始化。 什麼會導致我的按鈕不顯示?我已經檢查過,確保一切正常。

+1

不是你的問題的原因,但只是一個說明,你應該通常使用按鈕'UIControlEventTouchUpInside'控制事件,而不是觸及。這是一種更好的用戶體驗,因爲只有當您在按鈕內釋放手指時纔會執行操作,並讓您有機會取消操作。 –

+0

謝謝。我現在將切換。希望有人回答這個問題。有很多關於此的帖子,但似乎沒有解決我的問題。 – Shawn

+1

這個代碼在你的viewController中嗎?你在哪裏打電話? –

回答

5

你可以試試這個:

button = [UIButton buttonWithType: UIButtonTypeSystem]; 

,然後設置框架是這樣的:

button.frame = CGRectMake(0,0,20,20); 

的UIButton的buttonWithType:方法在一個點上固定我的問題。不知道它是否會在這種情況下有所作爲。只是要嘗試。

+1

如果它解決了您的問題,則應將其標記爲接受的答案。 – Wez

+0

不客氣! :) –

+1

從iOS 7開始,不推薦使用'UIButtonTypeRoundedRect' - 應該使用'UIButtonTypeSystem'。 [文檔](https://developer.apple.com/library/ios/documentation/uikit/reference/UIButton_Class/UIButton/UIButton.html#//apple_ref/doc/uid/TP40006815-CH3-SW35) –

相關問題