移动UIImageView移动整个视图

时间:2014-08-23 04:31:42

标签: ios objective-c cocoa-touch uiimageview uikit

所以我试图让一些块(称为障碍物)从屏幕顶部掉落。这很有效,但是我的代码也会将整个视图向下移动......

ViewController.h:

@interface ViewController : UIViewController{
IBOutlet UIImageView * obstacle;
IBOutlet UIImageView * block;
NSTimer * obstacleTimer;
NSTimer * obMoveTimer;
}
-(void)obTimer;
-(void)moveOb;

ViewController.m:

- (void)obTimer{
UIImageView *cloneImageView = [[UIImageView alloc] initWithImage:obstacle.image];
cloneImageView.frame = CGRectMake(0, -20, obstacle.frame.size.width,     obstacle.frame.size.height);
cloneImageView.alpha = obstacle.alpha;
cloneImageView.layer.opacity = obstacle.layer.opacity;
cloneImageView.clipsToBounds = obstacle.clipsToBounds;
cloneImageView.backgroundColor = obstacle.backgroundColor;
cloneImageView.tintColor = obstacle.tintColor;
cloneImageView.contentMode = obstacle.contentMode;
cloneImageView.highlighted = obstacle.highlighted;
cloneImageView.opaque = obstacle.opaque;
cloneImageView.userInteractionEnabled = obstacle.userInteractionEnabled;
cloneImageView.multipleTouchEnabled = obstacle.multipleTouchEnabled;
cloneImageView.autoresizesSubviews = obstacle.autoresizesSubviews;
cloneImageView.layer.zPosition = obstacle.layer.zPosition+1;
cloneImageView.tag = numOb + 1;
numOb++;
cloneImageView.hidden = NO;
[obstacle.superview addSubview:cloneImageView];
}
- (void)moveOb{
    for (int i = 0; i <= numOb; i++){
        UIImageView *viewToAnimate = (UIImageView *)[obstacle.superview viewWithTag:i];
        viewToAnimate.center = CGPointMake(viewToAnimate.center.x, viewToAnimate.center.y + 1);
    }
}
- (void)viewDidLoad {
    obstacleTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self         selector:@selector(obTimer) userInfo:nil repeats:YES];
    obMoveTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self     selector:@selector(moveOb) userInfo:nil repeats:YES];
    obstacle.hidden = YES;
    [super viewDidLoad];
}

所以蓝色块正在倒下,整个视图也是如此。这是一张图片:

enter image description here

1 个答案:

答案 0 :(得分:0)

这些标签可能会导致您出现问题。默认情况下,UIView的{​​{1}}为0.因此,当您调出tag时,您确定自己获得了所需的viewWithTag吗?

我曾经多次使用过标签,通常用于同一视图中的不同内容。通常我会为此obstacle #define宏,并将它们分开,有点像

TAG_START_

每次我分配标签时,我都会使用

#define TAG_START_OBSTACLE 10000

要重新获得指数,

NSInteger tag = indexIWantToUse + TAG_START_OBSTACLE;

虽然我必须说,因为我在这里看不到NSInteger index = tag - TAG_START_OBSTACLE; 的定义,我认为有更好的方法来获取容器obstacle而不是使用{{1} }}。也许UIView obstacle.superview属性?在其中的容器,或者一些UIViewController你可以保持指针?