Help with stock ticker style scrolling using Core Animation - objective-c

I'm looking for some guidance on the best way to implement stock ticker style right-to-left scrolling of CALayers in Core Animation on OSX. I'm pretty new to Cocoa and don't know the best way to implement this.
I have a continuous stream of news items and stock details that I turn into CALayers (made up of 1 image and a CATextLayer) and I want to animate the CALayers from right to left of my custom view.
The news and stock information is constantly updating so I would like to add 1 item at a time to the view, scroll it right to left until the right-most point of the CALayer is showing, then add another CALayer to the view and start scrolling that as well. I would like to do this dynamic updating instead of taking a big snapshot of all my data, turning it into a big horizontal CALayer and scrolling that.
I'm looking for guidance on how to achieve this sort of effect -
do I manually animate each new CALayer along a path in the view? Or should I be using CAScrollLayer to achieve this effect?
Many thanks
Glen.

I'd do this with Quartz Composer and put a QCView in your app. It's a lot less work than you imagine.

You perhaps don't need to customize anything to do this. Here self is an object of class extending UIScrollView and with a UILabel to display the text.
////
//Header
#import <UIKit/UIKit.h>
#interface TickerScrollView : UIScrollView
- (void)displayText:(NSString *)string;
- (void)clearTicker;
#property (nonatomic, retain, readwrite) UILabel *textLabel;
#end
//////
//Implementation
#implementation TickerScrollView
#synthesize textLabel;
- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
// Initialization code
[self setFrame: frame];
[self setBounces: NO];
[self setShowsVerticalScrollIndicator:NO];
[self setShowsHorizontalScrollIndicator:NO];
[self setBackgroundColor:[UIColor greenColor]];
[self initialiseTextLabel];
}
return self;
}
- (void)initialiseTextLabel {
textLabel = [[UILabel alloc] initWithFrame:self.bounds];
[textLabel setTextAlignment:UITextAlignmentLeft];
[textLabel setNumberOfLines:1];
[textLabel sizeToFit];
[self addSubview:textLabel];
[self setScrollEnabled:YES];
}
- (void)displayText:(NSString *)string {
[self clearTicker];
[textLabel setText:string];
[textLabel sizeToFit];
[self beginAnimation];
}
- (void)clearTicker {
[textLabel setText:#""];
[textLabel sizeToFit];
CGPoint origin = CGPointMake(0, 0);
[self setContentOffset:origin];
}
- (void)beginAnimation {
CGFloat text_width = textLabel.frame.size.width;
CGFloat display_width = self.frame.size.width;
if ( text_width > display_width ) {
CGPoint origin = CGPointMake(0, 0);
[self setContentOffset:origin];
CGPoint terminal_origin = CGPointMake(textLabel.frame.size.width - self.frame.size.width, textLabel.frame.origin.y);
float duration = (text_width - display_width)/40;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveLinear];
[UIView setAnimationDelay:1.0];
[UIView setAnimationDuration:duration];
[self setContentOffset:terminal_origin];
[UIView commitAnimations];
}
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
- (void)dealloc {
[textLabel release];
[super dealloc];
}
#end

Related

Does it make sense to add ATMHud to tabBarController.view

When i try to add ATMHud to uitableviewcontroller subview it does work but it doesn't disable the scrolling and if the tableview is not on top i can't see the hud view. What i did was added to teh tabBarController.view that works but i want find out if this is a good idea or later on i might have issues with it.
Another question is tabBarController.view frame is that the whole screen or just the bottom part. How come atmhud shows in the middle of the screen?
Thanks in advance!
Yan
============
Found a blog post that shows how to reset self.view and add tableview separately in uitableviewcontroller
UITableViewController and fixed sub views
- (void)viewDidLoad {
[super viewDidLoad];
if (!tableView &&
[self.view isKindOfClass:[UITableView class]]) {
tableView = (UITableView *)self.view;
}
self.view = [[[UIView alloc] initWithFrame:
[UIScreen mainScreen].applicationFrame] autorelease];
self.tableView.frame = self.view.bounds;
self.tableView.contentInset = UIEdgeInsetsMake(44.0, 0.0, 0.0, 0.0);
[self.view addSubview:self.tableView];
UIView *fixedBar = [[UIView alloc] initWithFrame:
CGRectMake(0.0, 0.0, self.view.bounds.size.width, 44.0)];
fixedBar.backgroundColor = [UIColor colorWithRed:
0.0 green:1.0 blue:0.0 alpha:0.7];
[self.view addSubview:fixedBar];
[fixedBar release];
}
After this when add hud to self.view you will be able to disable the tableview on the bottom.
Let me know if this a good way to setup the tableview
The problem with using the tab bar is that the hud is now modal, and the user cannot change the tab.
It sounds like the tableview is not your primary viewm, as it can get "covered up". If its not the primary view, then add the ATMHud to self.view. If the tableView is the same as self.view, then add a new transparent view to it, then add the HUD to that view.
The tabBarController.view is the view that hosts the tabbed views - if you want to see its size (or frame) log it using NSStringFromCGRect(self.tabBarController.frame);
EDIT: I just did a test, the ATMHud DOES block the UI. All I can think of is that you have not inserted it where you need to (at the top of current view's subviews.) I have a demo project where I do this:
hud = [[ATMHud alloc] initWithDelegate:self];
[self.view addSubview:hud.view];
[hud setCaption:#"Howdie"];
[hud setActivity:YES];
[hud show];
[hud hideAfter:5];
A button under the hud is not active - in fact nothing in the view is active (probably the Nav Bar would be live though)
If you want an ARCified and field tested version, you can grab it here
EDIT2: The solution to your problem is below. Note that ATMHud blocks clicks from getting to the table, and the code below stops the scrolling:
- (void)hudWillAppear:(ATMHud *)_hud
{
self.tableView.scrollEnabled = NO;
}
- (void)hudDidDisappear:(ATMHud *)_hud
{
self.tableView.scrollEnabled = YES;
}
Dump the views:
#import <QuartzCore/QuartzCore.h>
#import "UIView+Utilities.h"
#interface UIView (Utilities_Private)
+ (void)appendView:(UIView *)v toStr:(NSMutableString *)str;
#end
#implementation UIView (Utilities_Private)
+ (void)appendView:(UIView *)a toStr:(NSMutableString *)str
{
[str appendFormat:#" %#: frame=%# bounds=%# layerFrame=%# tag=%d userInteraction=%d alpha=%f hidden=%d\n",
NSStringFromClass([a class]),
NSStringFromCGRect(a.frame),
NSStringFromCGRect(a.bounds),
NSStringFromCGRect(a.layer.frame),
a.tag,
a.userInteractionEnabled,
a.alpha,
a.isHidden
];
}
#end
#implementation UIView (Utilities)
+ (void)dumpSuperviews:(UIView *)v msg:(NSString *)msg
{
NSMutableString *str = [NSMutableString stringWithCapacity:256];
while(v) {
[self appendView:v toStr:str];
v = v.superview;
}
[str appendString:#"\n"];
NSLog(#"%#:\n%#", msg, str);
}
+ (void)dumpSubviews:(UIView *)v msg:(NSString *)msg
{
NSMutableString *str = [NSMutableString stringWithCapacity:256];
if(v) [self appendView:v toStr:str];
for(UIView *a in v.subviews) {
[self appendView:a toStr:str];
}
[str appendString:#"\n"];
NSLog(#"%#:\n%#", msg, str);
}
#end

UIPageControl doesn't properly react to taps

In my TestApp, I created a class "Carousel" which should let me create a swipe menu with a UIPageControl in an easy way (by simply creating an instance of the class Carousel).
Carousel is a subclass of UIView
At init, it creates an UIView, containing UIScrollView, UIPageControl
I can add further UIViews to the scroll view
I don't know if this is the proper way to do it, but my example worked quite well in my TestApp. Swiping between pages works perfectly and the display of the current page in the UIPageControl is correct.
If there were not one single problem: The UIPageControl sometimes reacts to clicks/taps (I only tested in Simulator so far!), sometimes it doesn't. Let's say most of the time it doesn't. I couldn't find out yet when it does, for me it's just random...
As you can see below, I added
[pageControl addTarget:self action:#selector(pageChange:) forControlEvents:UIControlEventValueChanged];
to my code. I thought this would do the proper handling of taps? But unfortunately, pageChange doesn't get always called (so the value of the UIPageControl doesn't change every time I click).
I would appreciate any input on this because I couldn't find any solution on this yet.
This is what I have so far:
Carousel.h
#import <UIKit/UIKit.h>
#interface Carousel : UIView {
UIScrollView *scrollView;
UIPageControl *pageControl;
BOOL pageControlBeingUsed;
}
- (void)addView:(UIView *)view;
- (void)setTotalPages:(NSUInteger)pages;
- (void)setCurrentPage:(NSUInteger)current;
- (void)createPageControlAt:(CGRect)cg;
- (void)createScrollViewAt:(CGRect)cg;
#end
Carousel.m
#import "Carousel.h"
#implementation Carousel
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
// Create a scroll view
scrollView = [[UIScrollView alloc] init];
[self addSubview:scrollView];
scrollView.delegate = (id) self;
// Init Page Control
pageControl = [[UIPageControl alloc] init];
[pageControl addTarget:self action:#selector(pageChange:) forControlEvents:UIControlEventValueChanged];
[self addSubview:pageControl];
}
return self;
}
- (IBAction)pageChange:(id)sender {
CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * pageControl.currentPage;
frame.origin.y = 0;
[scrollView scrollRectToVisible:frame animated:TRUE];
NSLog(#"%i", pageControl.currentPage);
}
- (void)addView:(UIView *)view {
[scrollView addSubview:view];
}
- (void)createPageControlAt:(CGRect)cg {
pageControl.frame = cg;
}
- (void)setTotalPages:(NSUInteger)pages {
pageControl.numberOfPages = pages;
}
- (void)setCurrentPage:(NSUInteger)current {
pageControl.currentPage = current;
}
- (void)createScrollViewAt:(CGRect)cg {
[scrollView setPagingEnabled:TRUE];
scrollView.frame = cg;
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width*pageControl.numberOfPages, scrollView.frame.size.height);
[scrollView setShowsHorizontalScrollIndicator:FALSE];
[scrollView setShowsVerticalScrollIndicator:FALSE];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
float frac = scrollView.contentOffset.x / scrollView.frame.size.width;
NSUInteger page = lround(frac);
pageControl.currentPage = page;
}
#end
ViewController.m (somewhere in viewDidLoad)
Carousel *carousel = [[Carousel alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
for (int i=0; i<5; i++) {
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(i * 320, 0, 320, 420)];
UIColor *color;
if(i%3==0) color = [UIColor blueColor];
else if(i%3==1) color = [UIColor redColor];
else color = [UIColor purpleColor];
view.backgroundColor = color;
[carousel addView:view];
view = nil;
}
[carousel setTotalPages:5];
[carousel setCurrentPage:0];
[carousel createPageControlAt:CGRectMake(0,420,320,40)];
[carousel createScrollViewAt:CGRectMake(0,0,320,420)];
Your code is correct. Most likely the frame of your pageControl is pretty small, so theres not a lot of area to look for touch events. You would need to increase the size of the height of pageControl in order to make sure taps are recognized all of the time.

Multiple NSImages in NSView?

Is it possible to draw multiple NSImages in a single NSView?
So far drawing in an NSView subclass is done like so:
- (void)drawRect:(NSRect)dirtyRect
{
[image drawInRect:NSMakeRect(0.0f, 0.0f, 100.0f, 100.0f) fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0f];
}
//to change the current image
- (void)newImage:(NSImage *)image_
{
[image release];
image = [image_ retain];
[self setNeedsDisplay:YES];
}
But this is for drawing just one image. Can anyone please help out?
Thanks.
You have to keep references to the images you need to draw.
#interface MyView : NSView
{
NSMutableArray* images;
}
Then, add the images with a suitable API, for example:
#implementation MyView
- (void) addImage: (NSImage *) anImage
{
[images addObject: anImage];
[self setNeedsDisplay: YES];
}
In drawRect: you can iterate through the images and draw all/some of them.

NSScrollview with NSGradient

I have a nsscroll view in my application and i made a subclass of nsscrollview to add a nsgradient but it doesn't work this is my code in my implementation file:
#import "scrollview.h"
#implementation scrollview
#synthesize startingColor;
#synthesize endingColor;
#synthesize angle;
- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self) {
// Initialization code here.
[self setStartingColor:[NSColor colorWithCalibratedRed:0.941 green:0.941 blue:0.941 alpha:1]];
[self setEndingColor:[NSColor colorWithCalibratedRed:0.6588 green:0.6588 blue:0.6588 alpha:1]];
[self setAngle:90];
}
return self;
}
- (void)drawRect:(NSRect)rect {
NSBezierPath* roundRectPath = [NSBezierPath bezierPathWithRoundedRect: [self bounds] xRadius:10 yRadius:10];
[roundRectPath addClip];
if (endingColor == nil || [startingColor isEqual:endingColor]) {
// Fill view with a standard background color
[startingColor set];
NSRectFill(rect);
}
else {
// Fill view with a top-down gradient
// from startingColor to endingColor
NSGradient* aGradient = [[NSGradient alloc]
initWithStartingColor:startingColor
endingColor:endingColor];
[aGradient drawInRect:[self bounds] angle:angle];
}
}
The first step is to create a custom NSView subclass that draws a gradient:
GradientBackgroundView.h:
#interface GradientBackgroundView : NSView
{}
#end
GradientBackgroundView.m:
#import "GradientBackgroundView.h"
#implementation GradientBackgroundView
- (void) drawRect:(NSRect)dirtyRect
{
NSGradient *gradient = [[[NSGradient alloc] initWithStartingColor:[NSColor redColor] endingColor:[NSColor greenColor]] autorelease];
[gradient drawInRect:[self bounds] angle:90];
}
#end
The next step is to make the scroll view's document view an instance of this class (instead of plain NSView).
In IB, double-click your scroll view, and in the Identity pane set the Class to GradientBackgroundView.
From this point on, things are handled pretty much in the standard way. You can add subviews to the document view, resize it, etc. Here's a screenshot:

Couldn't UIToolBar be transparent?

I try the following code, but it doesn't work.
[helloToolbar setBackgroundColor:[UIColor clearColor]];
To make a completely transparent toolbar, use the method described here. In a nutshell, create a new TransparentToolbar class that inherits from UIToolbar, and use that in place of UIToolbar.
TransarentToolbar.h
#interface TransparentToolbar : UIToolbar
#end
TransarentToolbar.m
#implementation TransparentToolbar
// Override draw rect to avoid
// background coloring
- (void)drawRect:(CGRect)rect {
// do nothing in here
}
// Set properties to make background
// translucent.
- (void) applyTranslucentBackground
{
self.backgroundColor = [UIColor clearColor];
self.opaque = NO;
self.translucent = YES;
}
// Override init.
- (id) init
{
self = [super init];
[self applyTranslucentBackground];
return self;
}
// Override initWithFrame.
- (id) initWithFrame:(CGRect) frame
{
self = [super initWithFrame:frame];
[self applyTranslucentBackground];
return self;
}
#end
(code from the blog post linked above)
In iOS 5, simply call setBackgroundImage and pass a transparent image.
Here's how I do it (I dynamically generate transparent image):
CGRect rect = CGRectMake(0, 0, 1, 1);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
CGContextFillRect(context, rect);
UIImage *transparentImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[toolbar setBackgroundImage:transparentImage forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
The best you can do is using
[helloToolbar setBarStyle:UIBarStyleBlack];
[helloToolbar setTranslucent:YES];
This will get you a black but translucent toolbar.
Transparent (iOS 5.0):
[toolbar setBackgroundImage:[[UIImage alloc] init] forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
Translucent:
[toolbar setBarStyle:UIBarStyleBlack];
[toolbar setTranslucent:YES];
A cumulative solution for all devices, from oldest iOS 3.0 (iPhone 1) to newest iOS 6.1 (iPad mini).
#implementation UIToolbar (Extension)
- (void)drawRect:(CGRect)rect
{
if (CGColorGetAlpha(self.backgroundColor.CGColor) > 0.f)
{
[super drawRect:rect];
}
}
- (void)setTransparent
{
//iOS3+
self.backgroundColor = [UIColor clearColor];
//iOS5+
if ([self respondsToSelector:#selector(setBackgroundImage:forToolbarPosition:barMetrics:)])
{
[self setBackgroundImage:[[UIImage new] autorelease] forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
}
//iOS6+
if ([self respondsToSelector:#selector(setShadowImage:forToolbarPosition:)])
{
[self setShadowImage:[[UIImage new] autorelease] forToolbarPosition:UIToolbarPositionAny];
}
}
#end
When you want a transparent toolbar, call setTransparent on it.
When you want a non-transparent toolbar, set a backgroundColor of your choice or add an imageView by yourself.
Another solution would be to define a category for UIToolbar:
#implementation UIToolbar(Transparent)
-(void)drawRect:(CGRect)rect {
// do nothing in here
}
#end
In the IB set the toolbar as Black Translucent and non opaque.
We've just noticed that overriding drawRect doesn't work anymore with iOS 4.3. It's not called anymore (edit: seems to be only in Simulator). Instead drawLayer:inContext: is called.
A great solution was posted here
Now you can set each UIToolbar object transparent, by setting its tintColor to [UIColor clearColor] :)
With iOS 5 the following works:
UIToolbar *bar = [[UIToolbar alloc] initWithFrame:CGRectZero];
if (bar.subviews.count > 0)
[[[bar subviews] objectAtIndex:0] removeFromSuperview];
This is because the background is now a subview. This code is safe even with new iterations of iOS, but it may stop working. This is not private API usage, your app is safe to submit to the store.
Make sure you remove the backgroundView before adding any UIBarButtonItems to the bar. Or my code will not work.
I just tested the following with iOS 4.3 on simulator and phone, seems to work fine. Subclass UIToolbar, provide one method:
- (void)drawRect:(CGRect)rect
{
[[UIColor colorWithWhite:0 alpha:0.6f] set]; // or clearColor etc
CGContextFillRect(UIGraphicsGetCurrentContext(), rect);
}
toolbar.barStyle = UIBarStyleBlackTranslucent;
This works in iOS5.1 with pretty minimal effort. I am matching up the size, as only the background will have the same frame size as the toolbar itself. You could use other criteria, of course.
Enjoy.
Create a subclass of UIToolbar as follows:
.h:
#import <UIKit/UIKit.h>
#interface UIClearToolbar : UIToolbar
#end
.m:
#import "UIClearToolbar.h"
#implementation UIClearToolbar
- (void)layoutSubviews {
// super has already laid out the subviews before this call is made.
[self.subviews enumerateObjectsUsingBlock:^(UIView* obj, NSUInteger idx, BOOL *stop) {
if (CGSizeEqualToSize(self.frame.size, obj.frame.size) ||
self.frame.size.width <= obj.frame.size.width) { // on device, the background is BIGGER than the toolbar.) {
[obj removeFromSuperview];
*stop = YES;
}
}];
}
#end
Thanks #morais for your solution - here's the code translated to MonoTouch:
public class TransparentToolbar : UIToolbar
{
public TransparentToolbar()
{
init();
}
public TransparentToolbar(RectangleF frame) : base(frame)
{
init();
}
void init()
{
BackgroundColor=UIColor.Clear;
Opaque=false;
Translucent=true;
}
public override void Draw(RectangleF rect)
{
}
}