如何使用Cocoa Touch动态创建UIButton?

时间:2012-03-29 05:28:17

标签: ios cocoa-touch

如何使用Cocoa Touch动态创建UIButtons?

4 个答案:

答案 0 :(得分: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 :(得分:1)

这很容易

UIImage * buttonImage = [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];

答案 2 :(得分: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);
}

答案 3 :(得分: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..
}

希望这可以帮助你.... :)