投放发件人参数 [英] Casting sender parameter

查看:90
本文介绍了投放发件人参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法接受发件人,并用UI按钮调用。如何让那个对象转换成UIImageView?基本上如何重新使用按钮的代码。

I have a method that accepts a sender and is called with a UIbutton. How do I get that object to casted into a UIImageView? Basically how do I re-use the code for the button.

- (IBAction)startClick:(id)sender { 
    button.animationImages = [NSArray arrayWithObjects:
                                       [UIImage imageNamed:@"Pic_1.png"],
                                       [UIImage imageNamed:@"Pic_2.png"],
                                       [UIImage imageNamed:@"Pic_3.png"],
                                       nil];
    [button setAnimationRepeatCount:1];
    button.animationDuration = 1;
    [button startAnimating];
}


推荐答案

我的第一个回应是可能是一个错误这样做。 UIButton UIImageView <$ c $的不同子类c> UIView (和 UIButton UIControl ),所以他们只有共同的东西是 UIView 方法。如果 sender 确实是 UIButton ,将其视为 UIImageView 很可能会导致错误,例如无法识别的选择器发送到实例等。

My first response is that it's probably a mistake to do so. UIButton and UIImageView are distinct subclasses of UIView (and UIButton is a subclass of UIControl) so the only things they have in common are UIView methods. If sender is really a UIButton, treating it as a UIImageView is likely to result in errors, such as "unrecognized selector sent to instance" and the like.

一般来说,更清洁的解决方案是创建一个单独的方法对 UIImageView 的操作。 (与Java不同,Objective-C和Cocoa不喜欢将UI响应代码放到基于事件类型的单个方法中 - 而是基于需要发生的操作来逻辑组织代码。)

In general, a cleaner solution is to create a separate method that is the action for a UIImageView. (Unlike Java, Objective-C and Cocoa prefer to not shoehorn UI response code into a single method based on the event type — rather, you organize the code logically based on the operation that needs to happen.)

如果你必须从按钮和图像视图调用这个方法,你可以这样分离逻辑:

If you must call this method from both buttons and image views, you can separate the logic like this:

- (IBAction) startClick:(id)sender {
  if ([sender isKindOfClass:UIButton]) {
    ...
  }
  else if ([sender isKindOfClass:UIImageView]) {
    ...
  }
}

这篇关于投放发件人参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆