如何以编程方式将UIButton添加到UIToolBar?

iam*_*toc 5 iphone uibutton uitoolbar ios programmatically-created

我使用Interface Builder添加了工具栏,但我需要在运行时/有条件地添加按钮.我没有收到任何错误,但我的动态按钮没有出现在工具栏上.我已经验证arrayOfModulesScreens加载了我需要的数据.至少那可行(:)).我是否需要将按钮添加到UIView中,然后将该视图添加到工具栏中?只是想出来.也许有一个更好的方法开始?提前感谢任何导致决心的线索.

CustomFormController.h

@interface CustomFormController : UIViewController { 
    UIToolbar *screensBar;  
}
Run Code Online (Sandbox Code Playgroud)

CustomFormController.m

EPData *epData = [[EPData alloc] init];
NSArray *screens = [epData loadPlistIntoArray:@"Screens"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"process_module_id == %@", process_modulesID];
NSArray *arrayOfModulesScreens = [screens filteredArrayUsingPredicate:predicate];

for(int i=0; i < [arrayOfModulesScreens count]; i++) {
    NSDictionary *dictRow = [arrayOfModulesScreens objectAtIndex:i];
    UIButton *button = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
    [button setTitle:[dictRow objectForKey:@"screen_title"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [screensBar addSubview:button];  
}
Run Code Online (Sandbox Code Playgroud)

Ano*_*mie 8

如果您实际上想要将UIBarButtonItem(而不是UIButton)添加到工具栏,则只需创建一个或多个UIBarButtonItem,将它们放在NSArray(或NSMutableArray)中,并将该数组分配给items工具栏的属性.有关详细信息,请参阅UIBarButtonItem文档.使用上面的代码,可能看起来像这样:

    NSMutableArray *items = [NSMutableArray array];
    for (int i = 0; i < [arrayOfModulesScreens count]; i++) {
        NSDictionary *dictRow = [arrayOfModulesScreens objectAtIndex:i];
        UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithTitle:[dictRow objectForKey:@"screen_title"]
                                                                   style:UIBarButtonItemStyleBordered
                                                                  target:self
                                                                  action:@selector(buttonClick:)];
        [items addObject:button];
        [button release];
    }
    screensBar.items = items;
Run Code Online (Sandbox Code Playgroud)

(当然,你需要改变你buttonClick:的期望UIBarButtonItem而不是UIButton).

如果您真的想在其中放置U​​IButton,首先需要将UIButton包装在UIBarButtonItem中,如下所示:

UIBarButtonItem *item = [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];
Run Code Online (Sandbox Code Playgroud)

然后将项目添加到工具栏,如上所示.


至于为什么你的按钮没有显示在你发布的代码中,问题是UIButton buttonWithType:创建了一个零宽度和零高度的按钮.您需要调整按钮的大小(手动或sizeToFit在设置标题后使用)以使其显示.修好之后,您会看到父视图左上角的按钮全部位于彼此之上; 您需要根据需要手动定位它们.