【问题标题】:How do I access programmatically created buttons?如何访问以编程方式创建的按钮?
【发布时间】:2012-04-25 22:10:38
【问题描述】:

我正在像这样向导航栏添加多个按钮。

UIToolbar* tools = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 133, 44.01)];

NSMutableArray* buttons = [[NSMutableArray alloc] initWithCapacity:2];
UIBarButtonItem *bi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(assignSelected)];
bi.style = UIBarButtonItemStyleBordered;

[bi setEnabled:FALSE];

[buttons addObject:bi];
[buttons addObject:self.editButtonItem];

[tools setItems:buttons animated:NO];

self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:tools];

self.editButtonItem.title = @"Select";

基本上我这样做是为了让他们可以使用编辑按钮来选择一组项目并对它们采取行动。我想启用我在编辑时添加的操作按钮。我有以下方法来控制按钮在编辑时所说的内容。

- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];

    if (editing)
    {
        self.editButtonItem.title = NSLocalizedString(@"Cancel", @"Cancel");
    }
    else
    {
        self.editButtonItem.title = NSLocalizedString(@"Select", @"Select");
    }
}

这就是我要启用和禁用操作按钮的地方。我不确定如何访问该按钮,因为它是以编程方式创建的。

【问题讨论】:

    标签: ios ios5 uinavigationbar uibarbuttonitem uinavigationitem


    【解决方案1】:

    您应该能够通过创建它时使用的“bi”变量来访问它。 bi 变量应该保存指向按钮的指针。所以你可以像这样调用那个按钮上的方法:

    [bi methodName:methodArg];

    【讨论】:

    • 再考虑一下您的问题后,我意识到您可能在从其他方法访问“bi”时遇到问题。在头文件中设置 UIBarButtonItem *bi 并使其等于 nil。 UIBarButtonItem *bi = nil; 然后在你的实现文件中,去掉类和指针,并从你的头文件中初始化变量。 bi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(assignSelected)]; 那么类中的所有方法都应该可以访问它。
    • 这么明显的答案,我早该想到的。
    猜你喜欢
    • 2023-03-25
    • 1970-01-01
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-29
    • 1970-01-01
    相关资源
    最近更新 更多