2012-03-29 51 views
0

我該如何動態創建可可觸摸UIButtons?我該如何動態創建與Cocoa Touch的UIButtons?

+0

' (int i = 0; i <10; i ++){UIButton * but = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [self.view addSubview:but]; }',這會創建按鈕,但這應該在沒有多少研究的情況下找到,您面臨什麼問題? – iNoob 2012-03-29 05:33:11

+0

嘿@Vicky,請先搜索,然後發佈問題.... :) – Krunal 2012-03-29 05:34:39

回答

1
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    myButton.frame = CGRectMake(20, 20, 200, 44); // position in the parent view and set the size of the button 
    [myButton setTitle:@"Click Me!" forState:UIControlStateNormal]; 
    // add targets and actions 
    [myButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside]; 
    // add to a view 
    [superView addSubview:myButton]; 

問題得以解決

快樂編碼

1

這是很容易

的UIImage *按鈕畫面= [UIImage的imageNamed:@ 「的TabBar - refresh.png」];

refresh = [UIButton buttonWithType:UIButtonTypeCustom]; 
refresh.frame = CGRectMake(frame values); 
[refresh setBackgroundImage:buttonImage forState:UIControlStateNormal]; 
[refresh addTarget:self action:@selector(refreshPressed:) forControlEvents:UIControlEventTouchUpInside];  
[self.view addSubview:refresh]; 
0

這裏是代碼...

UIButton *btnDone; 
btnDone = [UIButton buttonWithType:UIButtonTypeCustom]; 
[btnDone setFrame:CGRectMake(0, 0, 28, 29)]; 

// For setting an image to button.... 
[btnDone setImage:[UIImage imageNamed:@"done.png"] forState:UIControlStateNormal]; 
[btnDone setImage:[UIImage imageNamed:@"done_hover.png"] forState:UIControlStateHighlighted]; 

// Add target to button... 
[btnDone addTarget:self action:@selector(btnDoneAction:) forControlEvents:UIControlEventTouchUpInside]; 

//Method implementation.. 
-(void)btnDoneAction:(id)sender 
{ 
    //Your stuff.. 
} 

希望這有助於你.... :)

1

你可以做這樣的事情:爲

int yOfs = 0; 
for (int index = 0; index<10; index++) { 
    UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
    [aButton setBackgroundImage:[UIImage imageNamed:@"buttonImage"] forState:UIControlStateNormal]; 
    [aButton setTitle:[NSString stringWithFormat:@"Button %d",index] forState:UIControlStateNormal]; 
    [aButton setFrame:CGRectMake(20, yOfs, 100, 50)]; 
    [aButton addTarget:self action:@selector(aButtonClicked:) forControlEvents:UIControlEventTouchUpInside]; 
    [aView addSubview:aButton]; 

    yOfs += 50; 
} 


- (IBAction)aButtonClicked:(id)sender 
{ 
    NSLog(@"Clicked on button with title %@",[sender titleLabel].text); 
} 
+0

最好將您的按鈕存儲在一個數組爲例 – Gargo 2012-03-29 06:55:59