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

Posted

技术标签:

【中文标题】如何使用 Cocoa Touch 动态创建 UIButton?【英文标题】:How can I dynamically create UIButtons with Cocoa Touch? 【发布时间】:2012-03-29 05:28:17 【问题描述】:

【问题讨论】:

for(int i=0;i<10;i++) UIButton*but=[UIButton buttonWithType: UIButtonTypeRoundedRect]; [self.view addSubview:but]; ,这将创建按钮,但这应该很少研究就能找到,你面临什么问题? 嘿@Vicky,请先搜索,然后发布问题....:) 【参考方案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];

【讨论】:

【参考方案2】:
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】:
  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];

【讨论】:

【参考方案4】:
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..

【讨论】:

以上是关于如何使用 Cocoa Touch 动态创建 UIButton?的主要内容,如果未能解决你的问题,请参考以下文章

如何将用 Swift 编写的 Cocoa Touch 框架导入 .pch 文件?

我如何在 Cocoa Touch 库中使用故事板

从 swift cocoa touch 框架导入 jwt

构建纯 Swift Cocoa Touch 框架

UI - Cocoa Touch框架

如何解决 Cocoa touch 框架中的符号名称冲突