【问题标题】:Associate UIVIew with UIButton in IBAction将 UIVIew 与 IBAction 中的 UIButton 关联
【发布时间】:2013-03-11 09:12:41
【问题描述】:

我有一个带有 6 个按钮和 6 个子视图的视图控制器(在情节提要中)。这些子视图连接到 IBOutlets 并命名为“mySubView1”、“mySubView2”等:

@property (weak, nonatomic) IBOutlet UIView *mySubView1;
@property (weak, nonatomic) IBOutlet UIView *mySubView2;

我想根据按下的按钮为子视图的 alpha 值设置动画。所有 6 个按钮都连接到同一个 IBAction(如下),每个按钮都有一个标签(1 到 6)。

如何动态获取子视图属性名?例如,mySubView1 if sender.tag = 1 例如,在下面的动画块中:

- (IBAction)animateSubviews:(id)sender {

[UIView animateWithDuration:0.4
                      delay: 0.0
                    options: UIViewAnimationOptionCurveEaseOut
                 animations:^{
                      self.mySubView1.alpha = 1;
                 }
                 completion:^(BOOL finished){

                 }];

}

所以我需要的是:self.mySubView[sender tag].alpha = 1 之类的东西,但我很难过,所以非常感谢任何建议。

非常感谢

【问题讨论】:

    标签: ios uiview


    【解决方案1】:

    1) 为子视图分配标签

    将标签分配给您的UIViews,例如,与标签为 1 的按钮对应的视图可能有标签 101。

    - (IBAction)animateSubviews:(id)sender {
    
    [UIView animateWithDuration:0.4
                          delay: 0.0
                        options: UIViewAnimationOptionCurveEaseOut
                     animations:^{
                          UIView *subview = [self.view viewWithTag:((UIButton*)sender).tag + 100]; 
                          subview.alpha = 1;
                     }
                     completion:^(BOOL finished){
    
                     }];
    }
    

    2) 使用动态选择器(回答您的原始问题)

    您可以使用返回SEL 的方法NSSelectorFromString

    UIView *subview = [self performSelector:NSSelectorFromString([NSString stringWithFormat:@"mySubView%d", ((UIButton*)sender).tag])];
    

    【讨论】:

    • 非常感谢,看起来其中任何一个都可以。
    【解决方案2】:
    @property (strong, noatomatic) NSArray* arrayForSubViews;
    
    if (!self.arrayForSubViews) {
        self.arrayForSubViews = @[ self.mySubView1, self.mySubView2, ... ];
    }
    
    //get the second view
    self.arrayForSubViews[1];
    

    【讨论】:

    • 不错的解决方案,非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-04
    • 2014-07-18
    • 2014-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多