如何获得UIButton目标,动作和控制事件?

时间:2011-03-03 15:32:56

标签: iphone

我正在使用UIBmageView和UIButton一大堆。所以,我创建了一个自定义类来永久地将这两个结合起来,使事情变得更简单一些。这一切都运行良好,直到我决定实现 - (id)initWithObject:(AUIImageViewButton *)imageViewButton。

显然,我需要从传递的imageViewButton对象中复制所有相关属性。 UIImageView根本没有问题。这样的事情处理它:

imageview = [[UIImageView alloc] initWithFrame:imageViewButton.imageview.frame];        // Copy all relevant data from the source's imageview
[imagebutton.imageview setBackgroundColor:imageViewButton.imageview.backgroundColor];   //
[imagebutton.imageview setImage:imageViewButton.imageview.image];                       //

大部分按钮内容也随时可用:

button = [UIButton buttonWithType:imageViewButton.button.buttonType];                   // Copy all relevant data from the source's button
button.frame = imageViewButton.imageview.frame;                                         // 
[button setTitle:imageViewButton.button.titleLabel.text forState:UIControlStateNormal]; //
button.tag = imageViewButton.button.tag;                                                //

我在弄清楚如何获取addTarget:action:forControlEvents方法的所有数据时遇到了一些麻烦。

查看文档,我可以看到我可以使用UIControl的allControlEvents和allTargets方法。我现在就深入研究它,看看我能遇到多少麻烦。我不确定的是行动。

任何人都可以向我推进正确的方向吗?

谢谢,

-Martin

3 个答案:

答案 0 :(得分:32)

UIControl的allTargetsallControlEvents是开始的方式。最后一块拼图是actionsForTarget:forControlEvent:,为每个目标和事件调用一次。

答案 1 :(得分:20)

展示如何迭代按钮的目标并在另一个按钮上创建选择器的副本。具体的例子就是touchupinside事件,但这通常都是我使用的。

for (id target in button.allTargets) {
     NSArray *actions = [button actionsForTarget:target
                                      forControlEvent:UIControlEventTouchUpInside];
     for (NSString *action in actions) {
          [newButton addTarget:target action:NSSelectorFromString(action) forControlEvents:UIControlEventTouchUpInside];
     }
}

答案 2 :(得分:0)

在分配新的目标/操作之前,我使用它来删除任何可能不需要的目标/操作:

if let action = button.actions(forTarget: target, forControlEvent: .touchUpInside)?.first
{
    button.removeTarget(target, action: NSSelectorFromString(action), for: .touchUpInside)
}

或者如果你真的想删除所有操作:

if let actions = button.actions(forTarget: target, forControlEvent: .touchUpInside)
{
    for action in actions
    {
        button.removeTarget(target, action: NSSelectorFromString(action), for: .touchUpInside)
    }
}
相关问题