-1

我目前正在设计一个需要动态创建对象然后在 ViewController 中显示它们的应用程序。我的问题是浏览文档以尝试创建我需要的对象。我已经进行了一些搜索,甚至试图坐下来弄清楚,但是唉,我没有什么可以展示的。我已经知道如何动态创建 ViewController 但我似乎无法在其中获取任何对象。

有谁知道我如何在 XCode 中使用 Objective-C 动态创建对象(比如按钮和滑块)?

4

1 回答 1

1

在代码中创建一个按钮很简单

- (void)addButton {

    // Create button
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];

    // Set the frame (location and size)
    [button setFrame:CGRectMake(0, 0, 40, 30)];

    // Set what happens when you touch the button
    [button addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];

    // Set button text
    [button.titleLabel setText:@"Button"];

    // Add button to view
    [self.view addSubview:button];

}

许多界面元素遵循类似的模式分配并初始化对象,设置框架并将其添加到视图中。

于 2012-06-21T23:19:16.550 回答