UIImageView дрейфует на viewDidLoad - PullRequest
1 голос
/ 16 ноября 2009

Я программно добавляю UIImageView и UILabel к нескольким экранам в программе, над которой я работаю. Поэтому я написал UIViewController, который содержит код для загрузки UIImageView и UILabel в viewDidLoad, а также таймер для обновления содержимого. Я использую этот контроллер представления как суперкласс для любых представлений, которым нужны UIImageView и UILabel.

По большей части это работает нормально, но при переходе от определенных экранов пара, кажется, начинается с кадра (0,0,0,0) и медленно анимируется к определенному кадру. Я понятия не имею, в чем проблема или даже где искать. Любые указатели здесь были бы великолепны.

Вот код, который я использую в качестве суперкласса.

FoundationViewController.h

#import 

@interface FoundationViewController : UIViewController {
    IBOutlet UIImageView *activeInventoryImage;
    IBOutlet UILabel *activeInventoryLabel;
    NSTimer *inventoryStatusTimer;
}

@property (nonatomic, retain) IBOutlet UIImageView *activeInventoryImage;
@property (nonatomic, retain) IBOutlet UILabel *activeInventoryLabel;

- (void) advanceToView:(id)nextView;
- (void) inventoryStatus;
- (BOOL) inventoryActive:(NSDate*)inventoryExpire withImage:(NSString*)imageName;   
@end

FoundationViewController.m

#import "FoundationViewController.h"
#import "GameData.h"
#import "Globals.h"


@implementation FoundationViewController

@synthesize activeInventoryImage;
@synthesize activeInventoryLabel;

- (void) viewDidLoad{

    // initialize the active inventory icon and label
    activeInventoryImage = [[UIImageView alloc] init];
    activeInventoryLabel = [[UILabel alloc] init];

    // clear
    activeInventoryImage.image = [UIImage imageNamed:@""];
    activeInventoryLabel.text = @"";

    // set the center points
    activeInventoryImage.frame = CGRectMake(258, 7, 20, 20);
    activeInventoryLabel.frame = CGRectMake(280, 6, 30, 20);

    // set label parameters
    activeInventoryLabel.backgroundColor = [UIColor clearColor];
    activeInventoryLabel.font = [UIFont fontWithName:@"Helvetica" size:11.0f];
    activeInventoryLabel.textColor = [UIColor colorWithRed:0.2 green:0.4 blue:0.6 alpha:1];

    // add to view
    [self.view addSubview:activeInventoryImage];
    [self.view addSubview:activeInventoryLabel];

    // start the timer if there is any active inventory
    if(
       [self inventoryActive:[GameData sharedGameData].player.inventory.aExpire withImage:@"a.png"] || 
       [self inventoryActive:[GameData sharedGameData].player.inventory.bExpire withImage:@"b.png"] || 
       [self inventoryActive:[GameData sharedGameData].player.inventory.cExpire withImage:@"c.png"]
       )
        inventoryStatusTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(inventoryStatus) userInfo:nil repeats:YES];

    [super viewDidLoad];
}

- (BOOL) inventoryActive:(NSDate*)inventoryExpire withImage:(NSString*)imageName{
    NSTimeInterval expireSeconds;
    NSDateFormatter *formatter;
    BOOL runTimer = FALSE;

    // expire
    expireSeconds = [inventoryExpire timeIntervalSinceNow];
    if(expireSeconds > 0){
        formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"mm:ss"];
        NSDate *expireTime = [NSDate dateWithTimeIntervalSince1970:expireSeconds];
        activeInventoryImage.image = [UIImage imageNamed:imageName];
        activeInventoryLabel.text = [formatter stringFromDate:expireTime];
        [formatter release];
        runTimer = TRUE;
    }

    return runTimer;
}

- (void) inventoryStatus{

    // if there is no active inventory kill the timer
    if(
       ![self inventoryActive:[GameData sharedGameData].player.inventory.aExpire withImage:@"a.png"] && 
       ![self inventoryActive:[GameData sharedGameData].player.inventory.bExpire withImage:@"b.png"] && 
       ![self inventoryActive:[GameData sharedGameData].player.inventory.cExpire withImage:@"c.png"]
       ){   
        activeInventoryImage.image = [UIImage imageNamed:@""];
        activeInventoryLabel.text = @"";
        if(inventoryStatusTimer != nil)
            [inventoryStatusTimer invalidate];
    }

}

- (void) advanceToView:(id)nextView{
    if([nextView isKindOfClass:[UIView class]]){
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:2.7];
        [UIView setAnimationTransition:UIViewAnimationTransitionNone forView:self.view cache:YES];
        [self.view addSubview:nextView];
        [UIView commitAnimations];
    }
    else
        NSLog(@" Error Loading View: %@",nextView);
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [activeInventoryImage removeFromSuperview];
    [activeInventoryImage release];
    [activeInventoryLabel release];
    [super dealloc];
}


@end

Ответы [ 2 ]

1 голос
/ 16 ноября 2009

Установите точку останова в advanceToView, так как это, кажется, ваш единственный анимационный код. Каждый раз, когда он вызывается, смотрите на стек вызовов в отладчике. Отсюда вы можете увидеть, что вызывает этот код, когда он не должен быть.

0 голосов
/ 16 ноября 2009

После некоторых экспериментов, обнаруженных мной, initWithFrame исправляет проблему дрейфа.

activeInventoryImage = [[UIImageView alloc] initWithFrame:CGRectMake(258, 7, 20, 20)];
activeInventoryLabel = [[UILabel alloc] initWithFrame:CGRectMake(280, 6, 30, 20)];

Я до сих пор не знаю, в чем причина проблемы. Если бы кто-нибудь мог сказать мне, что здесь происходит, я бы хотел узнать об этом в будущем.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...