2012-03-29 97 views
1

我試圖做出一個操作,每次按下按鈕時,都會向視圖添加一個按鈕。我沒有嘗試過的作品。從IBAction以編程方式添加UIButton

如果有人能夠清理該做什麼,這將是非常感謝。

這是在我的按鈕添加按鈕的最近一次嘗試:

-(IBAction) addButton{ 
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 
    button.frame = CGRectMake(10,10,50,50); 
    button.tag = 1; 

    [button addTarget:self 
       action:@selector(buttonTouched:) 
    forControlEvents:UIControlEventTouchUpInside]; 
    [view addSubview:button]; 
} 
+0

您確定調用該方法嗎? – Alexander 2012-03-29 04:53:39

+0

檢查IBAction是否正確接線。有時趕時間,我們錯過了綁定動作/ iboutlets ... – 2012-03-29 04:56:10

+0

還要確保'view'不是'nil'。 – Costique 2012-03-29 05:04:24

回答

6
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
button.frame = CGRectMake(10,10,50,50); 
button.tag = 1; 
[button addTarget:self action:@selector(buttonTouched:) forControlEvents:UIControlEventTouchUpInside]; 
[self.view addSubview:button]; 

Try the above codes. 
+0

有一個警告,說本地聲明的'按鈕'隱藏實例變量......是好嗎? – nfoggia 2012-03-29 15:05:53

1

您需要添加此

#import <QuartzCore/CoreAnimation.h> 

然後做遵循這個

-(IBAction)buttonTouched:(id)sender{ 
     NSLog(@"New Button Clicked"); 
    } 
    -(IBAction)addButton:(id)sender 
    { 
     UIButton *btnallstates; 
     UIImage *statesbtnimg=[UIImage imageNamed:@"1.png"]; 
     btnallstates=[[UIButton buttonWithType:UIButtonTypeCustom]retain]; 
     btnallstates.tag=1; 
     btnallstates.frame=CGRectMake(103, 127, 193, 31); 
     [btnallstates.layer setBorderWidth:0]; 
     [btnallstates addTarget:self action:@selector(buttonTouched:)  forControlEvents:UIControlEventTouchUpInside]; 
     [btnallstates setBackgroundImage:statesbtnimg forState:UIControlStateNormal]; 
     [self.view addSubview:btnallstates]; 

    } 
1

你的代碼是正確的。僅此行

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 

改變

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 

顯示視圖上的按鈕。

UIButtonTypeCustom雖然被添加到視圖中,但不會顯示出來。

你可以通過改變按鈕的顏色來理解這一點。 例如將代碼更改爲此。

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 
button.backgroundColor=[UIColor redColor]; 

希望它有效。請享用。

0
Try this 

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
[button addTarget:self 
     action:@selector(aMethod:) 
    forControlEvents:UIControlEventTouchUpInside]; 
[button setTitle:@"Show View" forState:UIControlStateNormal]; 
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0); 
[self.view addSubview:button]; 
相關問題