如何以编程方式替换 IB 中内置的 UIToolBar 项

发布于 2024-07-25 21:33:32 字数 176 浏览 9 评论 0原文

我有一个带有各种图像按钮的工具栏,是在 Interface Builder 中创建的。

我希望能够在按下时以编程方式将其中一个按钮替换为活动指示器,然后放回原始按钮,但在活动完成时将其颜色从白色更改为黄色。

这可以通过 IB 构建的工具栏实现吗?还是我必须考虑以编程方式构建整个工具栏和自定义视图?

I have a toolbar with various image buttons, created in Interface Builder.

I'd like to be able to programmatically replace one of the buttons with an activity indicator when pressed, and then put back the original button but change its color from white to yellow when the activity completes.

Is this possible with an IB built toolbar or must I look at building the whole toolbar programmatically and custom views?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

海的爱人是光 2024-08-01 21:33:33

自从这些答案发布以来,许多事情都发生了变化 这是一个 Swift 2.0 解决方案。

您要替换的原始 UIBarButtonItem 是如何以编程方式创建的并不重要。 您所需要的只是 UIToolbar 出口。 例如,要替换左侧第二项,请执行以下操作:

var toolbarItems = self.toolbar.items
let newItem = UIBarButtonItem(barButtonSystemItem: .Play, target: self, action: "play")
toolbarItems![1] = newItem
self.toolbar.setItems(toolbarItems, animated: true)

Swift

Much has changed since these answers have been posted. Here is a Swift 2.0 solution.

It matters not how the original UIBarButtonItem you are replacing has been created programmatically. All you need is the UIToolbar outlet. To replace, say, the 2nd item from the left, do this:

var toolbarItems = self.toolbar.items
let newItem = UIBarButtonItem(barButtonSystemItem: .Play, target: self, action: "play")
toolbarItems![1] = newItem
self.toolbar.setItems(toolbarItems, animated: true)
绾颜 2024-08-01 21:33:33

Swift 有一个更简单的方法。 就我而言,每次触摸时我都会切换播放按钮和暂停按钮。

@IBAction func playandPause(sender: UIBarButtonItem) { // Here we are creating an outlet. Hook this up to the bar button item.
    for (index, button) in toolbarItems!.enumerate() { // Enumerating through all the buttons
        if button === sender { // === operator is used to check if the two objects are the exact same instance in memory.
            var barButtonItem: UIBarButtonItem!
            if mediaplayer.playing {
                mediaplayer.pause()
                barButtonItem = UIBarButtonItem.init(barButtonSystemItem: .Play, target: self, action: #selector(playandPause(_:)))
            }else {
                mediaplayer.play()
                barButtonItem = UIBarButtonItem.init(barButtonSystemItem: .Pause, target: self, action: #selector(playandPause(_:)))
            }
            toolbarItems![index] = barButtonItem // Replace the old item with the new item.
            break // Break once we have found the button as it is unnecessary to complete the rest of the loop
        }
    }
}

Swift has a much easier way. In my case, I am switching the play button with the pause button every touch.

@IBAction func playandPause(sender: UIBarButtonItem) { // Here we are creating an outlet. Hook this up to the bar button item.
    for (index, button) in toolbarItems!.enumerate() { // Enumerating through all the buttons
        if button === sender { // === operator is used to check if the two objects are the exact same instance in memory.
            var barButtonItem: UIBarButtonItem!
            if mediaplayer.playing {
                mediaplayer.pause()
                barButtonItem = UIBarButtonItem.init(barButtonSystemItem: .Play, target: self, action: #selector(playandPause(_:)))
            }else {
                mediaplayer.play()
                barButtonItem = UIBarButtonItem.init(barButtonSystemItem: .Pause, target: self, action: #selector(playandPause(_:)))
            }
            toolbarItems![index] = barButtonItem // Replace the old item with the new item.
            break // Break once we have found the button as it is unnecessary to complete the rest of the loop
        }
    }
}
人事已非 2024-08-01 21:33:33

我认为这应该是可能的。 您可以尝试在 ViewController 类中为该特定按钮创建 IBOutlet,并将该按钮从 IB 连接到该插座,或者您可以使用该 UIToolbar 实例的 items 属性(您确实有一个对此的引用,不是吗? ?)并在其中找到适当的项目,使用修改后的项目创建一个新的 NSArray,并将其设置回该toolbar.items 属性。

华泰

I think it should be possible. You might either try creating an IBOutlet for that specific button in your ViewController class, and connect the button from IB to that outlet, or you can use the items property of that UIToolbar instance (you do have a reference to that, don't you?) and find the appropriate item in there, create a new NSArray with modified items, and set it back on that toolbar.items property.

HTH

情仇皆在手 2024-08-01 21:33:33

关于这一点的注释 - 工具栏会去除图标中的任何颜色,因此您仍然无法将其设置为黄色。 您需要更改图像形状以指示“打开”。

或者,您需要使用 UIButtons 加载 BarButtonItems(使用 initWithCustomView)并适当地设置按钮的图像。

华泰

A note on this - the toolbar will strip out any color in your icons, so you still won't be able to make it yellow. You'll need to change the image shape to indicate "on" instead.

Alternatively you'll need to load your BarButtonItems with UIButtons (use the initWithCustomView) and set the image of the button appropriately.

HTH

热鲨 2024-08-01 21:33:33

尝试:

- (void)setTitle:(NSString *)title forItem:(int)item ofToolbar:(UIToolbar *)tb {
    NSMutableArray *newItems = [tb.items mutableCopy];
    UIBarButtonItem *old = [newItems objectAtIndex:1],
    *titled = [[UIBarButtonItem alloc] initWithTitle:title style:old.style target:old.target action:old.action];

    [newItems  replaceObjectAtIndex:1 withObject:titled];
    tb.items = newItems;

    [titled release];
}

Try:

- (void)setTitle:(NSString *)title forItem:(int)item ofToolbar:(UIToolbar *)tb {
    NSMutableArray *newItems = [tb.items mutableCopy];
    UIBarButtonItem *old = [newItems objectAtIndex:1],
    *titled = [[UIBarButtonItem alloc] initWithTitle:title style:old.style target:old.target action:old.action];

    [newItems  replaceObjectAtIndex:1 withObject:titled];
    tb.items = newItems;

    [titled release];
}
坏尐絯 2024-08-01 21:33:33

对于您在 IB 中创建的整个工具栏(也就是说,不是各个工具栏项),创建一个 IBOutlet:

@IBOutlet weak var toolbarThatYouMade: UIToolbar!

这是一个各个工具栏项的数组,因此您可以使用 [0] 索引:

toolbarThatYouMade.items![0].image = UIImage(named: "New Image")

此代码假设您的资源中有一个名为“New Image”的图像。

然后,您可以触发工具栏项目的图像更改,而无需访问该特定项目本身; 例如,如果您将其用于媒体播放器之类的东西,您可以从以下位置切换暂停/播放图像:
a) 暂停/播放按钮本身,
b) 停止按钮,
c) 当您收到玩家状态更改的通知时,

d) 完全是别的东西。 (勇敢!大胆!做一些以“b”开头的东西!)

For the entire toolbar that you created in IB (that is to say, not the individual toolbar items), create an IBOutlet:

@IBOutlet weak var toolbarThatYouMade: UIToolbar!

This is an array of individual toolbar items, so you would access the leftmost member (for example) with a [0] index:

toolbarThatYouMade.items![0].image = UIImage(named: "New Image")

This code assumes that you have an image named "New Image" in your assets.

You can then trigger an image change for a toolbar item without having to access that specific item itself; for example, if you were using this for something like a media player, you could toggle pause/play images from:
a) the Pause/Play button itself,
b) the Stop button,
c) when you are notified of a change of player state,
or
d) something else entirely. (Be brave! Be bold! Be something else that begins with 'b'!)

蓝梦月影 2024-08-01 21:33:32

这是我在类似情况下所做的一个例子。 我想使用 Interface Builder 构建工具栏,但根据是否“选中”来切换 BarButtonItems 之一。 在此示例中,有一些关键事项需要注意。 在头文件中为该类定义了以下 2 个成员变量:

NSMutableArray *toolbarItems;
IBOutlet UIToolbar *toolbar;
NSUInteger checkUncheckIndex;

当我想要更新选中状态时,我调用此函数...请注意,定义了一个名为 checkUncheckClicked 的选择器,当特定按钮在单击 UIToolbar。 UIToolbar 被设置为工具栏的 IBOutlet。 或者,您可以将 UIBarButtonItem 连接为插座本身,并使用它作为您的逻辑来识别按钮的索引,或者就此而言,如果事情不会随着时间的推移而改变,您可以对按钮的索引进行硬编码。 最后,项目中包含了一个checked.png 和unchecked.png 可供交替使用。

- (void)updateBarButtonItemChecked:(BOOL)checked {
    if (toolbarItems == nil) {
        toolbarItems = [[NSMutableArray arrayWithArray:toolbar.items] retain];
        checkUncheckIndex = -1;

        for (NSUInteger i = 0; i < [toolbarItems count]; i++) {
            UIBarButtonItem *barButtonItem = [toolbarItems objectAtIndex:i];
            if (barButtonItem.action == @selector(checkUncheckClicked)) {
                favoriteIndex = i;
                break;
            }
        }
    }

    if (checkUncheckIndex != -1) {
        UIBarButtonItem *barButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:checked ? @"checked.png" : @"unchecked.png"] 
                                                                           style:UIBarButtonItemStylePlain target:self action:@selector(checkUncheckClicked)] autorelease];
        [toolbarItems replaceObjectAtIndex:checkUncheckIndex withObject:barButtonItem];

        toolbar.items = toolbarItems;
    }
}

当然,toolbarItems 和工具栏应该在类的 dealloc 中释放。

希望这可以帮助!

Here is an example of what I did in a similar situation. I wanted to build the toolbar using Interface Builder but toggle one of the BarButtonItems based on whether or not it was "checked". In this example, there are a few key things to note. The following 2 member variables are defined for the class in the header file:

NSMutableArray *toolbarItems;
IBOutlet UIToolbar *toolbar;
NSUInteger checkUncheckIndex;

When I want to update the checked status, I call this function... Please note that there is a selector defined called checkUncheckClicked that is called when the particular button in the UIToolbar is clicked. And the UIToolbar is set up as an IBOutlet to toolbar. Alternately, you could hook up the UIBarButtonItem as an outlet itself and use that as your logic to identify the index of the button, or for that matter, you could hard-code the index of the button if things won't change over time. Finally, there is a checked.png and unchecked.png to alternate between that is included in the project.

- (void)updateBarButtonItemChecked:(BOOL)checked {
    if (toolbarItems == nil) {
        toolbarItems = [[NSMutableArray arrayWithArray:toolbar.items] retain];
        checkUncheckIndex = -1;

        for (NSUInteger i = 0; i < [toolbarItems count]; i++) {
            UIBarButtonItem *barButtonItem = [toolbarItems objectAtIndex:i];
            if (barButtonItem.action == @selector(checkUncheckClicked)) {
                favoriteIndex = i;
                break;
            }
        }
    }

    if (checkUncheckIndex != -1) {
        UIBarButtonItem *barButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:checked ? @"checked.png" : @"unchecked.png"] 
                                                                           style:UIBarButtonItemStylePlain target:self action:@selector(checkUncheckClicked)] autorelease];
        [toolbarItems replaceObjectAtIndex:checkUncheckIndex withObject:barButtonItem];

        toolbar.items = toolbarItems;
    }
}

And, of course toolbarItems and toolbar should be released in your dealloc for the class.

Hope this helps!

呆橘 2024-08-01 21:33:32

这是我使用的方法
完全以编程方式管理工具栏似乎要简单得多,所以......

在视图控制器中声明 1 组或多组 UIBarButtonItem 项作为属性项,还将工具栏声明并连接为 UIToolbar 属性。 还要声明 1 个或多个数组来保存项目。

在实施中
在 viewDidLoad 中分配并设置你的 UIBarButtonItems 例如

       playButton = [[UIBarButtonItem alloc]
         initWithBarButtonSystemItem:UIBarButtonSystemItemPlay 
    target:self 
action:@selector(handlePlayClick)];

灵活的按钮(用于对齐等)是这样声明的

   flexButton1 =[[UIBarButtonItem alloc]
 initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace 
target:nil action:nil];

有几种 initMethods 来处理不同类型的按钮工具栏支持。 全部遵循与上面类似的语法。 值得注意的是目标和行动的设置。 Target:通常是 self,action 是按钮应触发的功能的名称。

分配 UIBarButtons 后,使用 initWithObjects 将它们添加到数组中。

然后,要将按钮分配给工具栏,您可以调用

[toolbar setItems:<array name>];

不要忘记在代码末尾释放 UIBarButtons 和数组。

希望这可以帮助。 如果您需要更多代码,请告诉我。

里奇·D.

Here is the approach I used
It seemed to be much simpler to manage the toolbar entirely programatically so ....

In your view controller declare 1 or more sets of UIBarButtonItem items as property items also declare and hookup the toolbar as a UIToolbar property. Also declare 1 or more arrays to hold the items.

In the implementation
In viewDidLoad alloc and set your UIBarButtonItems for example

       playButton = [[UIBarButtonItem alloc]
         initWithBarButtonSystemItem:UIBarButtonSystemItemPlay 
    target:self 
action:@selector(handlePlayClick)];

Flexible buttons (for alignment etc) are declared like this

   flexButton1 =[[UIBarButtonItem alloc]
 initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace 
target:nil action:nil];

There are several initMethods to handle the different types of buttons toolbars support. All follow a syntax similar to the above. Worth noting is the target and action settings. Target: would normally be self, action is the name of the function that button should trigger.

After alloc'ng your UIBarButtons add them to an array using initWithObjects.

Then to assign the buttons to the toolbar you would call

[toolbar setItems:<array name>];

Dont forget to dealloc your UIBarButtons and arrays at the end of your code.

Hope this helps. If you need more code let me know.

Rich D.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文