Thứ Hai, 12 tháng 7, 2010

iPhone - Marquees

How to create a marquee text for an iPhone app

Posted by: twmeier on Jan 21, 2010
Tagged in: Programming , iPhone

In this blog, you will learn how to create a moving text field (also know as a marquee). Marquees are very convenient to show news, stock updates, sport scores etc..


In the .h file:
#import
@interface FirstViewController : UIViewController {

UIView *messageView;
UILabel *lblTime;
CGSize messageSize;
}
@end


In the .m file:

- (void)viewDidAppear:(BOOL)animated {
NSString *theMessage = @"Hello, my name is Enigo Montoya. You killed my father, prepare to die";
messageSize = [theMessage sizeWithFont:[UIFont systemFontOfSize:14.0]];
messageView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, messageSize.width, 19)]; //x,y,width,height
[messageView setClipsToBounds:YES]; // With This you prevent the animation to be drawn outside the bounds.
[self.view addSubview:messageView];
lblTime = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, messageSize.width, 19)]; //x,y,width,height
[lblTime setBackgroundColor:[UIColor darkGrayColor]];
lblTime.font = [UIFont systemFontOfSize:14];
[lblTime setText:theMessage];
[lblTime setTextAlignment:UITextAlignmentLeft];
lblTime.frame = CGRectMake(0, 0, messageSize.width, 19); //x,y,width,height
[messageView addSubview:lblTime];
float duration = messageSize.width / 60; // This determines the speed of the moving text.
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:duration];
[UIView setAnimationTransition:UIViewAnimationTransitionNone forView:messageView cache:YES];
lblTime.frame = CGRectMake(-messageSize.width, 0, messageSize.width, 19); //x,y,width,height
[UIView commitAnimations];
}

Thats all there is too it. Check out the comments in the code for further clues on how it works.

Không có nhận xét nào:

Đăng nhận xét