automatic UIScrollView with paging - objective-c

I have a UIScrollView with paging enabled. However i want this scrollview to scroll right when a certain amount of time has passed. Is there a easy way to implement this or do i need to use a timer and programmatically scroll the scrollview?
Something like this website has in its header: http://denederlandsewateren.nl/ [notice the text "De Nederlandse Wateren" changes each x seconds]

You need a little method to help you scroll to the exact page, this is not implemented, but it's very simple, let's assume your scrollview is called myScrollview
This assumes you're scrolling horizontally, you can switch the code to fit your needs
-(void)scrollToPage:(NSInteger)aPage{
float myPageWidth = [myScrollView frame].size.width;
[myScrollView setContentOffset:CGPointMake(aPage*myPageWidth,y) animated:YES];
}
Then you setup a timer to call this method every 5 seconds for example, like this:
[[NSTimer scheduledTimerWithTimeInterval:5
target:self
selector:#selector(scrollPages)
userInfo:Nil
repeats:YES] fire];
Next step is to create the method that will be fired by the timer and scroll to the next page, I called it -(void)scrollPages, it also requires that you have two global variables called currentPage and numberOfPages, both are of type NSInteger
-(void)scrollPages{
[self scrollToPage:currentPage%numberOfPages];
currentPage++;
}
If something doesn't make sense let me know !

Found this on stackoverflow
[scrollView setContentOffset:CGPointMake(x, y) animated:YES];
To do slideshows with UIScrollView, you arrange all images in the scroll view, set up a repeated timer, then -setContentOffset:animated: when the timer fires.

In your .h file create outlets for scrollview and paging
#property (weak, nonatomic) IBOutlet UIScrollView *sliderScrollView;
#property (weak, nonatomic) IBOutlet UIPageControl *sliderPageControll;
#property (nonatomic,strong) NSArray *sliderImagesArray;
#property (nonatomic,strong) NSString *sliderIndexString;
#property (nonatomic,strong) NSString *currentPageIndexString;
after that in your .m file
[self.sliderScrollView setPagingEnabled:YES];
[self.sliderScrollView setBounces:NO];
[self.sliderScrollView setAlwaysBounceVertical:NO];
[self.sliderScrollView setShowsHorizontalScrollIndicator:NO];
self.sliderScrollView.alwaysBounceVertical = NO;
NSArray *imagesArray = self.sliderImagesArray;
for (int i = 0; i < [imagesArray count]; i++){
CGFloat xOrigin = i * self.imageSliderScrollView.frame.size.width;
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(xOrigin, 0, self.sliderScrollView.frame.size.width, self.sliderScrollView.frame.size.height)];
imageView.userInteractionEnabled = YES;
NSString *imgStr = [serviceImgArray objectAtIndex:i];
NSString *bikeStr = [NSString stringWithFormat:#"%#", imgStr];
NSURL *imageURL = [NSURL URLWithString:[bikeStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[imageView sd_setImageWithURL:imageURL
placeholderImage:[UIImage imageNamed:#"profilepic_bg"]];
[imageView setContentMode:UIViewContentModeScaleAspectFill];
[self.sliderScrollView addSubview:imageView];
}
// for adding autorotate scrolling
[NSTimer scheduledTimerWithTimeInterval:5 target:self selector:#selector(autoStartSlide:) userInfo:nil repeats:YES];
self.sliderPageControll.numberOfPages = imagesArray.count;
self.sliderPageControll.currentPage = 0;
self.currentPageIndexString = [NSString stringWithFormat:#"%ld",(long)0];
[self.sliderScrollView setContentSize:CGSizeMake(self.sliderScrollView.frame.size.width * [imagesArray count], self.sliderScrollView.frame.size.height)];
if ([self.sliderPageControll respondsToSelector:#selector(setPageIndicatorTintColor:)]) {
self.sliderPageControll.currentPageIndicatorTintColor = [UIColor redColor];
self.sliderPageControll.pageIndicatorTintColor = [UIColor whiteColor];
}
CGRect frame = self.sliderScrollView.frame;
frame.origin.x = frame.size.width * [[NSString stringWithFormat:#"%#",self.sliderIndexString] integerValue];
frame.origin.y = 0;
[self.sliderScrollView scrollRectToVisible:frame animated:NO];
self.sliderPageControll.currentPage = [[NSString stringWithFormat:#"%#",self.sliderIndexString] integerValue];
after that implement scrollview delegate method
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
NSInteger scrollIndex = (NSInteger)(self.sliderScrollView.contentOffset.x / self.sliderScrollView.frame.size.width);
self.sliderPageControll.currentPage = scrollIndex;
self.currentPageIndexString = [NSString stringWithFormat:#"%ld",(long)self.sliderPageControll.currentPage];
}
Here implement your autotrotate method.
- (void)autoStartSlide:(id)sender {
if(pagger.numberOfPages > pagger.currentPage+1) {
[UIView animateWithDuration:0.5 animations:^{
slider.contentOffset = CGPointMake(slider.contentOffset.x + slider.frame.size.width, 0);
} completion:^(BOOL finished) {
}];
}
else {
slider.contentOffset = CGPointMake(slider.contentOffset.x - slider.frame.size.width, 0);
[UIView animateWithDuration:0.5 animations:^{
slider.contentOffset = CGPointMake(slider.contentOffset.x + slider.frame.size.width, 0);
} completion:^(BOOL finished) {
slider.contentOffset = CGPointMake(0, 0) ;
}];
}
}

Here is a Swift 5 Compatible one
var currentPage = 1;
var slideTimer : Timer?
ViewDidLoad
slideTimer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(scrollPages), userInfo: nil, repeats: true)
viewDidDisappear
slideTimer?.invalidate()
Functions
#objc func scrollPages() {
scrollToPage(page: CGFloat(currentPage%slides.count));
currentPage+=1;
}
func scrollToPage(page : CGFloat) {
let pageWidth = scrollView.frame.width
scrollView .setContentOffset(CGPoint(x: pageWidth * page, y: 0.0), animated: true)
}

Related

Specified the scroll of a UIScrollView with an UIProgressView

I would like to add a progress bar under the navigation bar which will indicate the progress of the scroll of a UIScrollView, I use (not work) : I do
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
self.progressView.progress = scrollView.contentOffset.y;
}
check now I created one demo:
#import "ViewController.h"
#interface ViewController ()<UIScrollViewDelegate>{
UIScrollView *scroll;
UIProgressView *indicater;
}
#end
#implementation ViewController
- (void)viewDidLoad {
indicater=[[UIProgressView alloc]initWithFrame:CGRectMake(0, 65, 320,10)];
indicater.backgroundColor=[UIColor redColor];
indicater.progress = 0.0;
indicater.hidden=false;
[self.view addSubview:indicater];
scroll=[[UIScrollView alloc]initWithFrame:CGRectMake(10, 80,300, 200)];
scroll.backgroundColor=[UIColor greenColor];
scroll.userInteractionEnabled=YES;
scroll.delegate=self;
scroll.contentSize = CGSizeMake(300 ,5000);
[self.view addSubview:scroll];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
CGPoint offset = scroll.contentOffset;
CGRect bounds = scroll.bounds;
CGSize size = scroll.contentSize;
UIEdgeInsets inset = scroll.contentInset;
float y = offset.y + bounds.size.height - inset.bottom;
float h = size.height;
NSLog(#"%f",y);
NSLog(#"%f",h);
NSNumber *num=[NSNumber numberWithFloat:y];
NSNumber *num1=[NSNumber numberWithFloat:h];
[self UpdateProgressbar:num TotalscrollLenrth:num1];
}
-(void)UpdateProgressbar:(NSNumber*)currentscrollLenrth TotalscrollLenrth:(NSNumber*)n
{
NSString *totalLength = [NSString stringWithFormat:#"%#", n];
NSLog(#"%#", totalLength);
NSString *currentScrool = [NSString stringWithFormat:#"%#", currentscrollLenrth];
NSLog(#"%#", currentScrool);
if (currentscrollLenrth <= n) {
[indicater setProgress:([currentScrool intValue]/[totalLength floatValue])];
}
else {
// do somithig
}
}

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.

How to add sound while UIScrollview is scrolling in iphone sdk?

This is my code for adding sound while UIScrollview is scrolling in iPhone SDK. In this code, how to add the sound while using touch-events in scrolling?
Please give me your idea and suggestion or sample.
const CGFloat kScrollObjHeight = 151.0;
const CGFloat kScrollObjWidth =320.0;
const NSUInteger kNumImages = 5;
- (void)layoutScrollImages
{
UIImageView *view = nil;
NSArray *subviews = [scrollView1 subviews];
CGFloat curXLoc = 0;
for (view in subviews)
{
if ([view isKindOfClass:[UIImageView class]] && view.tag > 0)
{
CGRect frame = view.frame;
frame.origin = CGPointMake(curXLoc, 0);
view.frame = frame;
curXLoc += (kScrollObjWidth);
}
}
[scrollView1 setContentSize:CGSizeMake((kNumImages * kScrollObjWidth), [scrollView1 bounds].size.height)];
}
- (void)viewDidLoad
{
self.view.backgroundColor = [UIColor clearColor];
[scrollView1 setBackgroundColor:[UIColor whiteColor]];
[scrollView1 setCanCancelContentTouches:NO];
scrollView1.indicatorStyle = UIScrollViewIndicatorStyleWhite;
scrollView1.clipsToBounds = YES;
scrollView1.scrollEnabled = YES;
scrollView1.pagingEnabled = YES;
NSUInteger i;
for (i = 1; i <= kNumImages; i++)
{
NSString *imageName = [NSString stringWithFormat:#"snap%d.jpg", i];
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
CGRect rect = imageView.frame;
rect.size.height = kScrollObjHeight;
rect.size.width = kScrollObjWidth;
imageView.frame = rect;
imageView.tag = i;
[scrollView1 addSubview:imageView];
[imageView release];
[self layoutScrollImages];
}
[super viewDidLoad];
}
add UIScrollViewDelegate to your interface and then play sound while the scrolling is in task in scrollViewWillBeginDragging state and stop scrolling while in scrollViewDidEndDragging state.
You can use AVAudioPlayer to play sound on iOS devices
UPDATE:
Tells the delegate when the scroll view is about to start scrolling the content.
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
Also, Tells the delegate when dragging ended in the scroll view.
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
Implement these in your code & put in your custom behavior
you mast use UIScrollViewDelegate method
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
//play sound here
}

Objective C implementing a UIPickerView with a "Done" button

I am trying to implement a "Done" button in a UIPickerView Similar to the one under this link
I looked in the class reference but I couldn t find it
Thanks
The easiest way to do it is to model it in Interface Builder. It is a UIView containing a UIToolbar and a UIPickerView.
Then create an outlet for the UIView and connect it.
If you then have a UITextField you can assign your custom view to its inputView property.
[self.textField setInputView:self.customPicker];
Alternatively you can add the picker to your main view...
- (void)viewDidLoad
{
[super viewDidLoad];
self.customPicker.frame = CGRectMake(0, CGRectGetMaxY(self.view.frame), CGRectGetWidth(self.customPicker.frame), CGRectGetHeight(self.customPicker.frame));
[self.view addSubview:self.customPicker];
}
... and then use this method to show or hide the picker.
- (void)setPickerHidden:(BOOL)hidden
{
CGAffineTransform transform = hidden ? CGAffineTransformIdentity : CGAffineTransformMakeTranslation(0, -CGRectGetHeight(self.customPicker.frame));
[UIView animateWithDuration:0.3 animations:^{
self.customPicker.transform = transform;
}];
}
I added a UIToolbar with a UIBarButtonItem for the 'done' button in my xib with the frame set so that it's not initially visible (y value equal to the height of the parent view).
Every time the user access the picker, I changed the frame (the y value) of the UIDatePicker and the UIToolbar with an animation so that it slides up along with the picker from the bottom of the screen similar to the keyboard.
Check out my code below.
- (IBAction)showPicker
{
if(pickerVisible == NO)
{
// create the picker and add it to the view
if(self.datePicker == nil) self.datePicker = [[[UIDatePicker alloc] initWithFrame:CGRectMake(0, 460, 320, 216)] autorelease];
[self.datePicker setMaximumDate:[NSDate date]];
[self.datePicker setDatePickerMode:UIDatePickerModeDate];
[self.datePicker setHidden:NO];
[self.view addSubview:datePicker];
// the UIToolbar is referenced 'using self.datePickerToolbar'
[UIView beginAnimations:#"showDatepicker" context:nil];
// animate for 0.3 secs.
[UIView setAnimationDuration:0.3];
CGRect datepickerToolbarFrame = self.datePickerToolbar.frame;
datepickerToolbarFrame.origin.y -= (self.datePicker.frame.size.height + self.datePickerToolbar.frame.size.height);
self.datePickerToolbar.frame = datepickerToolbarFrame;
CGRect datepickerFrame = self.datePicker.frame;
datepickerFrame.origin.y -= (self.datePicker.frame.size.height + self.datePickerToolbar.frame.size.height);
self.datePicker.frame = datepickerFrame;
[UIView commitAnimations];
pickerVisible = YES;
}
}
- (IBAction)done
{
if(pickerVisible == YES)
{
[UIView beginAnimations:#"hideDatepicker" context:nil];
[UIView setAnimationDuration:0.3];
CGRect datepickerToolbarFrame = self.datePickerToolbar.frame;
datepickerToolbarFrame.origin.y += (self.datePicker.frame.size.height + self.datePickerToolbar.frame.size.height);
self.datePickerToolbar.frame = datepickerToolbarFrame;
CGRect datepickerFrame = self.datePicker.frame;
datepickerFrame.origin.y += (self.datePicker.frame.size.height + self.datePickerToolbar.frame.size.height);
self.datePicker.frame = datepickerFrame;
[UIView commitAnimations];
// remove the picker after the animation is finished
[self.datePicker performSelector:#selector(removeFromSuperview) withObject:nil afterDelay:0.3];
}
}
I create a custom class, this supports multiple orientation:
DateTimePicker.h
#interface DateTimePicker : UIView {
}
#property (nonatomic, assign, readonly) UIDatePicker *picker;
- (void) setMode: (UIDatePickerMode) mode;
- (void) addTargetForDoneButton: (id) target action: (SEL) action;
#end
DateTimePicker.m
#define MyDateTimePickerToolbarHeight 40
#interface DateTimePicker()
#property (nonatomic, assign, readwrite) UIDatePicker *picker;
#property (nonatomic, assign) id doneTarget;
#property (nonatomic, assign) SEL doneSelector;
- (void) donePressed;
#end
#implementation DateTimePicker
#synthesize picker = _picker;
#synthesize doneTarget = _doneTarget;
#synthesize doneSelector = _doneSelector;
- (id) initWithFrame: (CGRect) frame {
if ((self = [super initWithFrame: frame])) {
self.backgroundColor = [UIColor clearColor];
UIDatePicker *picker = [[UIDatePicker alloc] initWithFrame: CGRectMake(0, MyDateTimePickerToolbarHeight, frame.size.width, frame.size.height - MyDateTimePickerToolbarHeight)];
[self addSubview: picker];
UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame: CGRectMake(0, 0, frame.size.width, MyDateTimePickerToolbarHeight)];
toolbar.barStyle = UIBarStyleBlackOpaque;
toolbar.autoresizingMask = UIViewAutoresizingFlexibleWidth;
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle: #"Done" style: UIBarButtonItemStyleBordered target: self action: #selector(donePressed)];
UIBarButtonItem* flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
toolbar.items = [NSArray arrayWithObjects:flexibleSpace, doneButton, nil];
[self addSubview: toolbar];
self.picker = picker;
picker.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin;
self.autoresizesSubviews = YES;
self.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin;
}
return self;
}
- (void) setMode: (UIDatePickerMode) mode {
self.picker.datePickerMode = mode;
}
- (void) donePressed {
if (self.doneTarget) {
[self.doneTarget performSelector:self.doneSelector withObject:nil afterDelay:0];
}
}
- (void) addTargetForDoneButton: (id) target action: (SEL) action {
self.doneTarget = target;
self.doneSelector = action;
}
Using custom view in your view controller:
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:#selector(buttonPressed:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:#"Show picker" forState:UIControlStateNormal];
button.frame = CGRectMake(100, 50, 100, 40.0);
[self.view addSubview:button];
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
picker = [[DateTimePicker alloc] initWithFrame:CGRectMake(0, screenHeight/2 - 35, screenWidth, screenHeight/2 + 35)];
[picker addTargetForDoneButton:self action:#selector(donePressed)];
[self.view addSubview:picker];
picker.hidden = YES;
[picker setMode:UIDatePickerModeDate];
}
-(void)donePressed {
picker.hidden = YES;
}
-(void)buttonPressed:(id)sender {
picker.hidden = NO;
}
Hope this helps. :)
There is a more elegant solution. I'm not sure if this is recent (as of iOS7), but this has been working for me splendidly.
TJDatePicker.h
#protocol TJDatePickerActionDelegate <NSObject>
- (void)cancel:(id)sender;
- (void)done:(id)sender;
#end
#interface TJDatePicker : UIDatePicker
#property (strong, nonatomic) UIView *navInputView;
#property (weak, nonatomic) id<TJDatePickerActionDelegate> actionDelegate;
#end
TJDatePicker.m
#import "TJDatePicker.h"
#interface TJDatePicker ()
#property (strong, nonatomic) TJButton *cancelButton;
#property (strong, nonatomic) TJButton *doneButton;
#end
#implementation TJDatePicker
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
[self updateSubviews];
}
return self;
}
- (void)layoutSubviews
{
[super layoutSubviews];
[self updateSubviews];
}
- (void)updateSubviews
{
self.navInputView.frame = CGRectMake(0, 0, self.width, 45);
self.cancelButton.frame = CGRectMake(5, 5, 80, 35);
CGFloat width = 80;
self.doneButton.frame = CGRectMake(CGRectGetMaxX(self.navInputView.frame) - width, self.cancelButton.frame.origin.y, width, self.cancelButton.height);
}
- (UIView *)navInputView
{
if (!_navInputView)
{
_navInputView = [[UIView alloc] init];
_navInputView.backgroundColor = [UIColor whiteColor];
self.cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.cancelButton setTitle:#"CANCEL" forState:UIControlStateNormal];
[self.cancelButton addTarget:self action:#selector(cancelButtonPressed) forControlEvents:UIControlEventTouchUpInside];
[_navInputView addSubview:self.cancelButton];
self.doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.doneButton setTitle:#"DONE" forState:UIControlStateNormal];
[self.doneButton addTarget:self action:#selector(doneButtonPressed) forControlEvents:UIControlEventTouchUpInside];
[_navInputView addSubview:self.doneButton];
}
return _navInputView;
}
- (void)cancelButtonPressed
{
[self.actionDelegate cancel:self];
}
- (void)doneButtonPressed
{
[self.actionDelegate done:self];
}
And then at implementation time...
self.datePicker = [[TJDatePicker alloc] init];
self.datePicker.actionDelegate = self;
self.textField.inputAccessoryView = self.datePicker.navInputView;
The key here is to use the inputAccessoryView of the UITextField that you are planning on setting the UIDatePicker to.
You get the "Done" button in the toolbar using the ActionSheetPicker. Its is a great alternative to building it yourself.
https://github.com/skywinder/ActionSheetPicker-3.0
Success! Ok, I would never suggest doing this, but here's where the done button is created in your particular tutorial code:
Looking at the storyboard, we can see that when you click the "Role" box within "AddPersonTVC.h" (class at the top right of the storyboard), it pops up a class called "RollPickerTVCell.h"
Looking into RollPickerTVCell.h, we notice that the whole class is a subclass of "CoreDataTableViewCell"
#interface RolePickerTVCell : CoreDataTableViewCell <UIPickerViewDataSource, UIPickerViewDelegate>
Looking at the class "CoreDataTableViewCell.m", we finally find our uibarbuttonitem!
UIBarButtonItem *doneBtn =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(done:)];
In case you are working on a Table View Cell and you are not using a UITextField (hence you won't be using the Accessory View), here's what I did:
I created a table view cell called GWDatePickerCell that looks like this (no .nib files involved).
GWDatePickerCell.h:
#import <UIKit/UIKit.h>
#interface GWDatePickerCell : UITableViewCell
#property (nonatomic, strong) UIDatePicker *datePicker;
#property (nonatomic, strong) UIToolbar *toolbar;
#property (nonatomic, strong) UIBarButtonItem *buttonDone;
#end
GWDatePickerCell.m:
#import "GWDatePickerCell.h"
#implementation GWDatePickerCell
- (id) initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
if(!(self=[super initWithStyle:style reuseIdentifier:reuseIdentifier])) return nil;
_datePicker = [[UIDatePicker alloc] init];
[_datePicker setMinuteInterval:5];
[_datePicker setDatePickerMode:UIDatePickerModeDateAndTime];
[self.contentView addSubview:_datePicker];
_toolbar = [[UIToolbar alloc] init];
_buttonDone = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:nil action:nil];
_toolbar.items = #[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil], _buttonDone];
[self.contentView addSubview:_toolbar];
return self;
}
- (void)layoutSubviews{
[super layoutSubviews];
CGRect r = self.contentView.bounds;
r.origin.y +=44;
r.size.height = 216;
CGRect tb = self.contentView.bounds;
tb.size.height = 44;
_datePicker.frame = r;
_toolbar.frame = tb;
}
#end
Now all I had to do when creating the cells in the Table View:
Specify the #selector for the Done button.
Set the correct cell height in heightForRowAtIndexPath

How to animate UILabel?

I'm using UILabel to display some dynamic text. Sometime its over lap the width of the label. I want to slide the text if the UILabel goes out of bound.
How do I do the sliding animation with UILabel? Any help?
Modifying my answer to address the short coming pointed out -
UILabel *label; //Previously initialized UILabel
float newX = 0.0;
float newY = 101.0f;
label.center = CGPointMake(newX, newY);
If you wanted to animate the movement, it's cake to add an animation block:
UILabel *label; //Previously initialized UILabel
float newX = 90.0f;
float newY = 101.0f;
[UIView transitionWithView:label
duration:0.5f
options:UIViewAnimationCurveEaseInOut
animations:^(void) {
label.center = CGPointMake(newX, newY);
}
completion:^(BOOL finished) {
// Do nothing
}];
Notice that we only animate the X coordinate as you want the label to slide.
When I had to do something similar, I did this.
Please notice that I'm tweening the alpha, not the position, but I hope this could help you:
[UIView animateWithDuration:0.3f animations:^{yourLabel.alpha = 0.f;}];
-(void)repeat{
[NSTimer scheduledTimerWithTimeInterval:8.0
target:self
selector:#selector(LabelAnimation)
userInfo:nil
repeats:YES];
}
-(void)LabelAnimation
{
NSArray *elements = [yourText componentsSeparatedByString:#","];
NSMutableArray *outputElements = [[NSMutableArray alloc] init];
for (int i=1;i<[elements count];i++)
[outputElements addObject:[elements objectAtIndex:i]];
NSString *outputString = [outputElements componentsJoinedByString:#","];
[UIView animateWithDuration:3.0f delay:0.2f options:UIViewAnimationOptionTransitionNone animations:^{
_header.labelHeaderName.text=outputString;
} completion:^(BOOL finished)
{
if (outputString.length == 0) {
_header.labelHeaderName.text=_strAddress(your saved address);
}
}];
}