UIPickerView with a Done button in Ipad - objective-c

I have faced one issue to display UIPickerView with a Done button in Ipad.
I done detailed researches though many links and blogs and got the suggestion as "display the UIPickerView from an UIActionSheet"
I saw many posts related this, however there is no good answers.So please dont close it as a duplicate.
Also i was able to get some good codes to do it and it worked fine in my Iphone devices.
However i were found a difficulty in Ipad devices.
The Action-Sheet is not displaying as a full view.
Please see the below screenshot.this was the result!!!
The code is used to do this is pasted below.
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
delegate:nil
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
[actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
CGRect pickerFrame = CGRectMake(0, 40, 0, 0);
UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:pickerFrame];
pickerView.showsSelectionIndicator = YES;
pickerView.dataSource = self;
pickerView.delegate = self;
[actionSheet addSubview:pickerView];
[pickerView release];
UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:#"Close"]];
closeButton.momentary = YES;
closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f);
closeButton.segmentedControlStyle = UISegmentedControlStyleBar;
closeButton.tintColor = [UIColor blackColor];
[closeButton addTarget:self action:#selector(dismissActionSheet:) forControlEvents:UIControlEventValueChanged];
[actionSheet addSubview:closeButton];
[closeButton release];
[actionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
[actionSheet setBounds:CGRectMake(0, 0, 320, 485)];
Then I have downloaded a excellent sample application from github through sample pickers
After the download, i have copied the classes only mandatory for me to my application.
The method they are using to show the UIPickerView+Done button through Action-Sheet is described below
ActionStringDoneBlock done = ^(ActionSheetStringPicker *picker, NSInteger selectedIndex, id selectedValue) {
if ([myLabel respondsToSelector:#selector(setText:)]) {
[myLabel performSelector:#selector(setText:) withObject:selectedValue];
}
};
ActionStringCancelBlock cancel = ^(ActionSheetStringPicker *picker) {
NSLog(#"Block Picker Canceled");
};
NSArray *colors = [NSArray arrayWithObjects:#"Red", #"Green", #"Blue", #"Orange", nil];//picker items to select
[ActionSheetStringPicker showPickerWithTitle:#"Select a Block" rows:colors initialSelection:0 doneBlock:done cancelBlock:cancel origin:myButton];
In the last line of code they have used the parameter as origin: and we can pass any objects (button,label etc) to it.
The Action-sheet will take origin as the passed object.
Here my issue came again :). I have used segment control to pick the time as per my conditions.
if i give mySegment as the origin parameter,the Action-sheet origin arrow will display from middle of my segment control.Not from the selected tab ,which is too bad and will give confusion to my valuable users.
So i have added individual labels under the segment sections and given it for the origin parameter of the mentioned method and i fixed my issue.
However i know its not a good fix :)
May i know is there any easy way to do it?
Is Apple support ActionSheet+UIPickerView+DoneButton in Ipad?
Any help on this issue is Appreciated

-(void)viewDidload
{
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button1.frame = CGRectMake(165,165, 135,35);
[button1 setTitle:#"Type #" forState:UIControlStateNormal];
[button1 addTarget:self action:#selector(button1) forControlEvents:UIControlEventTouchUpInside];
[s addSubview:button1];
}
-(void)button1
{
items1 =[[NSMutableArray alloc]initWithObjects:#"H",#"E",#"T",#"K",nil];
myPickerView1 =[[UIPickerView alloc] initWithFrame:CGRectMake(60,80,200,300)];
myPickerView1.transform = CGAffineTransformMakeScale(0.75f, 0.75f);
myPickerView1.delegate = self;
myPickerView1.dataSource = self;
myPickerView1.showsSelectionIndicator = YES;
myPickerView1.backgroundColor = [UIColor clearColor];
myPickerView1.tag=1;
[myPickerView1 selectRow:1 inComponent:0 animated:YES];
[self.view addSubview:myPickerView1];
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;
{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;
{
switch (pickerView.tag)
{
case 1:
return [items1 count];
break;
case 2:
return [items2 count];
break;
}
return 0;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
switch (pickerView.tag)
{
case 1:
return[items1 objectAtIndex:row];
break;
case 2:
return[items2 objectAtIndex:row];
break;
}
return 0;
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
switch (pickerView.tag)
{
case 1:
{
[button1 setTitle:[items1 objectAtIndex:row] forState:UIControlStateNormal];
}
break;
case 2:
{
[button2 setTitle:[items2 objectAtIndex:row] forState:UIControlStateNormal];
}break;
}
pickerView.hidden = YES;
}

You have to use UIPopOverController.
First, create a UIPickerViewController for iPhone. You need it for the nib, which will be pushed into the popOver. Initialize the picker in ViewWithPicker
.h
#import <UIKit/UIKit.h>
#class ViewWithPickerController;
#protocol PopoverPickerDelegate
#required
- (void) viewWithPickerController:(ViewWithPickerController*) viewWithPickerController didSelectValue:(NSString*) value;
#end
#interface ViewWithPickerController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource> {
IBOutlet UIPickerView *pickerView;
id<PopoverPickerDelegate> delegate;
NSMutableArray *array;
}
#property(nonatomic, retain) IBOutlet UIPickerView *pickerView;
#property(nonatomic, assign) id<PopoverPickerDelegate> delegate;
#end
.m, after you initialized the array in viewDidLoad, picker methods:
// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)picker {
return 1;
}
// returns the number of rows in each component.
- (NSInteger)pickerView:(UIPickerView *)picker numberOfRowsInComponent:(NSInteger)component {
return [array count];
}
//returns the string value for the current row
- (NSString *)pickerView:(UIPickerView *)picker titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return [array objectAtIndex:row];
}
//handle selection of a row
- (void)pickerView:(UIPickerView *)picker didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
NSString *value = [pickerView.delegate pickerView:picker titleForRow:row forComponent:component];
//notify the delegate about selecting a value
if(delegate != nil)
[delegate viewWithPickerController:self didSelectValue:value];
}
Then, import the viewWithPicker into your main class, create a button and give it this action:
- (IBAction) showPickerPopupAction:(id) sender {
self.viewWithPickerController = [[[ViewWithPickerController alloc] initWithNibName:#"ViewWithPicker" bundle:[NSBundle mainBundle]] autorelease];
viewWithPickerController.contentSizeForViewInPopover =
CGSizeMake(viewWithPickerController.view.frame.size.width, viewWithPickerController.view.frame.size.height);
viewWithPickerController.delegate = self;
self.popoverController = [[[UIPopoverController alloc]
initWithContentViewController:viewWithPickerController] autorelease];
[self.popoverController presentPopoverFromRect:popoverButtonForPicker.frame inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
popoverController.delegate = self;
}
And to select a specific value
- (void) viewWithPickerController:(ViewWithPickerController*) viewWithPickerController didSelectValue:(NSString*) value
{
yourLabel.text = [NSString stringWithFormat:#"%# ",value];
}

Use UIPopoverController for done button in picker, create a view controller class in which take a picker and add navigation cancel and done button.
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:nextViewController];
_datePickerPopover = [[UIPopoverController alloc] initWithContentViewController:navigationController];
nextViewController.datePickerPopover = _datePickerPopover;
_datePickerPopover.delegate=self;
[_datePickerPopover setPopoverContentSize:CGSizeMake(320, 453) animated:NO];
if (isSearchOpen) {
[_datePickerPopover presentPopoverFromRect:CGRectMake(btn.frame.origin.x+10+245, btn.frame.origin.y+100-scrollPointY, 44, 44) inView:self.splitViewController.view permittedArrowDirections:UIPopoverArrowDirectionLeft animated:YES];
}
else
{
[_datePickerPopover presentPopoverFromRect:CGRectMake(btn.frame.origin.x+10+245, btn.frame.origin.y+55, 44, 44) inView:self.splitViewController.view permittedArrowDirections:UIPopoverArrowDirectionLeft animated:YES];//
}

Try out below code for UIPicker View in iPad
-(IBAction)tDriveBtnPressed:(id)sender
{
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = NSDateFormatterMediumStyle;
txtDate.text = [NSString stringWithFormat:#"%#",
[df stringFromDate:[NSDate date]]];
[df release];
UIToolbar *pickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 300, 44)];
pickerToolbar.barStyle = UIBarStyleBlackOpaque;
[pickerToolbar sizeToFit];
NSMutableArray *barItems = [[NSMutableArray alloc] init];
UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(pickerDone:)];
[barItems addObject:doneBtn];
[doneBtn release];
[pickerToolbar setItems:barItems animated:YES];
[barItems release];
datePicker = [[UIDatePicker alloc] init];
datePicker.datePickerMode = UIDatePickerModeDate;
CGRect pickerRect = datePicker.bounds;
datePicker.bounds = pickerRect;
UIViewController* popoverContent = [[UIViewController alloc] init];
UIView* popoverView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 344)];
popoverView.backgroundColor = [UIColor whiteColor];
datePicker.frame = CGRectMake(0, 44, 320, 300);
[datePicker addTarget:self action:#selector(dateChange:) forControlEvents:UIControlEventValueChanged];
[popoverView addSubview:pickerToolbar];
[popoverView addSubview:datePicker];
popoverContent.view = popoverView;
//resize the popover view shown
//in the current view to the view's size
popoverContent.contentSizeForViewInPopover = CGSizeMake(320, 244);
//create a popover controller
popoverController = [[UIPopoverController alloc] initWithContentViewController:popoverContent];
CGRect popoverRect = [self.view convertRect:[tDriveBtn frame]
fromView:[tDriveBtn superview]];
popoverRect.size.width = MIN(popoverRect.size.width, 100) ;
popoverRect.origin.x = popoverRect.origin.x;
// popoverRect.size.height = ;
[popoverController
presentPopoverFromRect:popoverRect
inView:self.view
permittedArrowDirections:UIPopoverArrowDirectionAny
animated:YES];
//release the popover content
[popoverView release];
[popoverContent release];
}
-(void)dateChange:(id)sender
{
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = NSDateFormatterMediumStyle;
txtDate.text= [NSString stringWithFormat:#"%#",
[df stringFromDate:datePicker.date]];
[df release];
}
- (void)pickerDone:(id)sender
{
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = NSDateFormatterMediumStyle;
txtDate.text= [NSString stringWithFormat:#"%#",
[df stringFromDate:datePicker.date]];
[df release];
if (popoverController != nil) {
[popoverController dismissPopoverAnimated:YES];
self.popoverController=nil;
}
}

Related

UicollectionView didSelectItemAtIndexPath is not called in uiTableviewcell

I am working on chat view. For this I have used this code :Chat Code
This is working fine. Now I have used UIcollectionView in UItableViewCell. Collection view is working fine. But the issue is didselect method is not called of UICollectionView as well as UITableView. Please help me. I need your help very badly.
I have used this code in UITableViewCell Class:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
self.backgroundColor = [UIColor clearColor];
if ([[UIDevice currentDevice].systemVersion floatValue] < 7.0f) {
self.textLabel.backgroundColor = [UIColor whiteColor];
}
self.textLabel.font = [UIFont systemFontOfSize:14.0f];
self.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
self.textLabel.numberOfLines = 0;
self.textLabel.textAlignment = NSTextAlignmentLeft;
self.textLabel.textColor = [UIColor blackColor];
_timestampLabel = [[UILabel alloc] init];
_timestampLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
_timestampLabel.textAlignment = NSTextAlignmentCenter;
_timestampLabel.backgroundColor = [UIColor clearColor];
_timestampLabel.font = [UIFont systemFontOfSize:12.0f];
_timestampLabel.textColor = [UIColor colorWithRed:0.4 green:0.4 blue:0.4 alpha:1.0];
_timestampLabel.frame = CGRectMake(0.0f, 12, self.bounds.size.width, 18);
[self.contentView addSubview:_timestampLabel];
messageBackgroundView = [[UIImageView alloc] initWithFrame:self.textLabel.frame];
[self.contentView insertSubview:messageBackgroundView belowSubview:self.textLabel];
self.AvatarImageView = [[UIImageView alloc] initWithFrame:CGRectMake(5,10+TOP_MARGIN, 50, 50)];
[self.contentView addSubview:self.AvatarImageView];
CALayer * l = [self.AvatarImageView layer];
[l setMasksToBounds:YES];
[l setCornerRadius:self.AvatarImageView.frame.size.width/2.0];
self.selectionStyle = UITableViewCellSelectionStyleNone;
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
[self.collectionView registerNib:[UINib nibWithNibName:#"ImageCollection" bundle:nil] forCellWithReuseIdentifier:#"Cell"];
[self.collectionView setUserInteractionEnabled:YES];
self.collectionView.backgroundColor = [UIColor clearColor];
[self.contentView addSubview:self.collectionView];
[messageBackgroundView setUserInteractionEnabled:YES];
[self.contentView setUserInteractionEnabled:YES];
// UITapGestureRecognizer *lpgr // = [[UITapGestureRecognizer alloc] // initWithTarget:self action:#selector(tapRecognized:)]; // lpgr.numberOfTapsRequired
= 1; // lpgr.delegate = self; // [self.collectionView addGestureRecognizer:lpgr];
}
[self setUserInteractionEnabled:YES];
return self; }
In UIViewController I have used this code in tableView cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *L_CellIdentifier = #"SPHTextBubbleCell";
self.documentsArray = [[NSMutableArray alloc]init];
self.documentsArray = [[self.messagesArray objectAtIndex:indexPath.row]valueForKey:#"Attachments"];
SPHTextBubbleCell *cell = [tableView dequeueReusableCellWithIdentifier:L_CellIdentifier];
cell.userInteractionEnabled = YES;
if (cell == nil)
{
cell = [[SPHTextBubbleCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:L_CellIdentifier];
}
// cell.bubbletype=(([[[self.messagesArray objectAtIndex:indexPath.row]valueForKey:#"MessageFromId"]intValue] == 1))?#"LEFT":#"RIGHT";
if ([[[self.messagesArray objectAtIndex:indexPath.row]valueForKey:#"MessageFromId"]intValue] == 1) {
cell.bubbletype = #"RIGHT";
}
else
{
cell.bubbletype = #"LEFT";
}
[cell setBackgroundColor:[UIColor clearColor]];
cell.textLabel.text = [[self.messagesArray objectAtIndex:indexPath.row]valueForKey:#"Content"];
cell.textLabel.tag=indexPath.row;
NSString *dateString = [NSString stringWithFormat:#"%#",[self mfDateFromDotNetJSON:[[self.messagesArray objectAtIndex:indexPath.row]valueForKey:#"UpdatedOn"]]];
NSLog(#"dateString..%#",dateString);
NSString *myString = [NSString stringWithFormat:#"%#",dateString];
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd HH:mm:ss ZZZ";
NSDate *yourDate = [dateFormatter dateFromString:myString];
// NSTimeZone *utc = [NSTimeZone timeZoneWithAbbreviation:#"UTC"];
// [dateFormatter setTimeZone:utc];
dateFormatter.dateFormat = #"dd-MMM-yy HH:mm";
NSString *newString = [dateFormatter stringFromDate:yourDate];
NSLog(#"newString..%#",newString);
if ([self.documentsArray count]!=0)
{
cell.CustomDelegate = self;
[cell.collectionView setUserInteractionEnabled:YES];
[cell.collectionView setDelegate:self];
[cell.collectionView setDataSource:self];
cell.collectionView.delegate =self;
cell.collectionView.dataSource = self;
[cell.collectionView reloadData];
[cell.collectionView setHidden:NO];
[cell.collectionView setBackgroundColor:[UIColor clearColor]];
}
else
{
[cell.collectionView setHidden:YES];
}
cell.collectionView.tag =indexPath.row;
cell.timestampLabel.text = newString;
[cell.AvatarImageView sd_setImageWithURL:([[[self.messagesArray objectAtIndex:indexPath.row]valueForKey:#"MessageFromId"]intValue] == 1)?[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",imageURLLive,[[[self.messagesArray objectAtIndex:indexPath.row]valueForKey:#"SellerPicture"] valueForKey:#"PictureUrl"]]]:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",imageURLLive,[[[self.messagesArray objectAtIndex:indexPath.row]valueForKey:#"BuyerPicture"] valueForKey:#"PictureUrl"]]]
placeholderImage:[UIImage imageNamed:#"Nav-profile1.png"]];
return cell;
}
Thanks in advance.
If your problem is that your UICollectionView taps do not cause the UITableViewCell it is in to be selected then you can bypass this by subclassing UICollectionView and modifying the hitTest function to your liking.
See my answer here.
This one lets you tap on anything outside of collection view items to select the table cell, but collection view items themselves will block the taps and process them as needed.
Modifying the hitTest method wasn't working in my case. I decided to use UITapGestureRecognizer.
// Custom UITableViewCell
override func awakeFromNib() {
super.awakeFromNib()
let tapGR = UITapGestureRecognizer(target: self, action: #selector(collectionViewTapped(_:)))
tapGR.numberOfTapsRequired = 1
self.collectionView.addGestureRecognizer(tapGR)
}
func collectionViewTapped(gr: UITapGestureRecognizer) {
let point = gr.locationInView(self.collectionView)
if let indexPath = self.collectionView.indexPathForItemAtPoint(point) {
// Do stuff
}
}
Don't forget to set delegate and dataSource.
self.tableView.delegate = self;
self.tableView.dataSource = self;

UIPickerView with UIActionSheet IOS 8 stop working

Showing a UIPickerView with UIActionSheet in iOS8 not showing
-(void)showPicker{
/************************ FIXED please contact me on nfsarmento#hotmail.com if you need help to fix******//
actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
[actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
CGRect pickerFrame = CGRectMake(0, 40, 0, 0);
UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:pickerFrame];
pickerView.showsSelectionIndicator = YES;
switch((uint)currentDelegate){
case 0:{
pickerView.dataSource = propertyDelegate;
pickerView.delegate = propertyDelegate;
[pickerView selectRow:[propertyDelegate index] inComponent:0 animated:NO];
break;
}
case 1:{
pickerView.dataSource = regionDelegate;
pickerView.delegate = regionDelegate;
[pickerView selectRow:[regionDelegate index] inComponent:0 animated:NO];
break;
}
case 2:{
pickerView.dataSource = townDelegate;
pickerView.delegate = townDelegate;
[pickerView selectRow:[townDelegate index] inComponent:0 animated:NO];
break;
}
case 3:{
pickerView.dataSource = bedDelegate;
pickerView.delegate = bedDelegate;
[pickerView selectRow:[bedDelegate index] inComponent:0 animated:NO];
break;
}
case 4:{
pickerView.dataSource = bathDelegate;
pickerView.delegate = bathDelegate;
[pickerView selectRow:[bathDelegate index] inComponent:0 animated:NO];
break;
}
case 5:{
pickerView.dataSource = priceDelegate;
pickerView.delegate = priceDelegate;
[pickerView selectRow:[priceDelegate index1] inComponent:0 animated:NO];
[pickerView selectRow:[priceDelegate index2] inComponent:1 animated:NO];
break;
}
case 6:{
pickerView.dataSource = currencyDelegate;
pickerView.delegate = currencyDelegate;
[pickerView selectRow:[currencyDelegate index] inComponent:0 animated:NO];
break;
}
}
[actionSheet addSubview:pickerView];
UISegmentedControl *previousButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:NSLocalizedString(#"Previous", nil)]];
previousButton.momentary = YES;
previousButton.frame = CGRectMake(5.0f, 7.0f, 70.0f, 30.0f);
previousButton.segmentedControlStyle = UISegmentedControlStyleBar;
previousButton.tintColor = [UIColor blackColor];
UISegmentedControl *nextButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:NSLocalizedString(#"Next", nil)]];
nextButton.momentary = YES;
nextButton.frame = CGRectMake(80.0f, 7.0f, 70.0f, 30.0f);
nextButton.segmentedControlStyle = UISegmentedControlStyleBar;
nextButton.tintColor = [UIColor blackColor];
UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:NSLocalizedString(#"Done", nil)]];
closeButton.momentary = YES;
closeButton.frame = CGRectMake(240, 7.0f, 70.0f, 30.0f);
closeButton.segmentedControlStyle = UISegmentedControlStyleBar;
closeButton.tintColor = [UIColor colorWithRed:0.35f green:0.55f blue:1.5f alpha:1.0f];
[closeButton addTarget:self action:#selector(hidePicker) forControlEvents:UIControlEventValueChanged];
[previousButton addTarget:self action:#selector(previousPicker) forControlEvents:UIControlEventValueChanged];
[nextButton addTarget:self action:#selector(nextPicker) forControlEvents:UIControlEventValueChanged];
if(currentDelegate > 0)[actionSheet addSubview:previousButton];
if(currentDelegate < 6)[actionSheet addSubview:nextButton];
[actionSheet addSubview:closeButton];
[actionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
[actionSheet setBounds:CGRectMake(0, 0, 320, 485)];
}
-(void) nextPicker{
[self hidePicker];
currentDelegate++;
[self showPicker];
}
-(void) previousPicker{
[self hidePicker];
currentDelegate--;
[self showPicker];
}
-(void)hidePicker{
switch ((uint)currentDelegate) {
case 0:{
[tf_type setText: [propertyDelegate.values objectAtIndex: [propertyDelegate index]]];
_appDelegate.int_typeV = [propertyDelegate index];
break;
}
case 1:{
[tf_region setText: [regionDelegate.values objectAtIndex: [regionDelegate index]]];
_appDelegate.int_regionV = [regionDelegate index];
//Reset Town dropdown when a region is picked
_appDelegate.int_townV = 0;
townDelegate = [[TownDelegate alloc] init];
[self.tf_town setText: [townDelegate.values objectAtIndex: [_appDelegate int_townV]]];
break;
}
case 2:{
[tf_town setText: [townDelegate.values objectAtIndex: [townDelegate index]]];
_appDelegate.int_townV = [townDelegate index];
break;
}
case 3:{
[tf_numBed setText: [bedDelegate.values objectAtIndex: [bedDelegate index]]];
_appDelegate.int_numBedV = [bedDelegate index];
break;
}
case 4:{
[tf_numBath setText: [bathDelegate.values objectAtIndex: [bathDelegate index]]];
_appDelegate.int_numBathV = [bathDelegate index];
break;
}
case 5:{
NSString * priceString = [[NSString alloc] initWithFormat:#"%# - %#",
[priceDelegate.values objectAtIndex: [priceDelegate index1]],
[priceDelegate.values2 objectAtIndex: [priceDelegate index2]]];
[tf_price setText:priceString];
_appDelegate.int_minPriceV = [priceDelegate index1];
_appDelegate.int_maxPriceV = [priceDelegate index2];
break;
}
case 6:{
[tf_currency setText: [currencyDelegate.values objectAtIndex: [currencyDelegate index]]];
_appDelegate.int_currencyV = [currencyDelegate index];
break;
}
}
[popoverController dismissPopoverAnimated:YES];
popoverController = nil;
[self dismissActionSheet];
}
My picker view
#import "PropertyTypeDelegate.h"
#implementation PropertyTypeDelegate
#synthesize values;
-(id)init{
self = [super init];
[self loadData];
return self;
}
-(int)index{ return index;}
-(void) loadData{
NSArray* array = [[NSArray alloc] initWithObjects:
NSLocalizedString(#"No Preference", nil),
NSLocalizedString(#"Villa", nil),
NSLocalizedString(#"Town House", nil),
NSLocalizedString(#"Apartment", nil),
NSLocalizedString(#"Retail", nil),
NSLocalizedString(#"Labour Camp", nil),
NSLocalizedString(#"Office", nil),
NSLocalizedString(#"Warehouse", nil),
NSLocalizedString(#"Land Residential", nil),
NSLocalizedString(#"Hotel apartment", nil),
NSLocalizedString(#"Residential Building", nil),
nil];
self.values = array;
index = 0;
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
return [values count];
}
-(NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent: (NSInteger)component{ return [values objectAtIndex:row];
}
-(void)pickerView:(UIPickerView *) thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
index = (int) (NSInteger)row;
}
#end
The link provided above actually refers to Apple Doc where it has removed adding subview to UIActionSheet. In your code, you are doing similar thing by adding UIPickerView into UIActionSheet. So in iOS8 onwards, even if the view is added to UIActionSheet, the view returned is actually nil while displaying.
For this purpose you can use ActionSheetPicker-3.0.
Actually, it's not UIActionSheet anymore. But looks exactly the same, and that's why it works on iOS8.
Do let me know if this answers your query!

add tap to focus functionality to ZBarReaderViewController

I am using the zbarsdk to read the barcodes . It is working fine , but my problem is I have added the overlay view to the ZBarReaderViewController (reader in my code ). So now I tried to add the tap to focus functionality . But it is crashing . Below is my code . Thanks in advance . Any ideas would be grateful .
-(IBAction)scanBarCode:(id)sender
{
barcodeClicked = 1;
NSLog(#"TBD: scan barcode here...");
// ADD: present a barcode reader that scans from the camera feed
reader = [ZBarReaderViewController new];
reader.readerDelegate = self;
reader.supportedOrientationsMask = ZBarOrientationMaskAll;
ZBarImageScanner *scanner = reader.scanner;
// TODO: (optional) additional reader configuration here
// EXAMPLE: disable rarely used I2/5 to improve performance
[scanner setSymbology: ZBAR_I25
config: ZBAR_CFG_ENABLE
to: 0];
reader.showsZBarControls = NO;
UIView *ovlView = [[UIView alloc] init];
[ovlView setFrame:CGRectMake(0, 0, 320, 480)];
[ovlView setBackgroundColor:[UIColor clearColor]];
UIImageView *leftBracket = [[UIImageView alloc] init];
[leftBracket setFrame:CGRectMake(21, 100, 278, 15)];
[leftBracket setImage:[UIImage imageNamed:#"TopBracket.png"]];
UIImageView *rightBracket = [[UIImageView alloc] init];
[rightBracket setFrame:CGRectMake(21, 240, 278, 15)];
[rightBracket setImage:[UIImage imageNamed:#"BottomBracket.png"]];
UIToolbar *bottomBar = [[UIToolbar alloc] init];
[bottomBar setBarStyle:UIBarStyleBlackOpaque];
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone && [UIScreen mainScreen].bounds.size.height * [UIScreen mainScreen].scale >= 1136)
{
[bottomBar setFrame:CGRectMake(0, 524, 320, 44)];
}
else
[bottomBar setFrame:CGRectMake(0, 436, 320, 44)];
UIBarButtonItem *cancel = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:#selector(cancelCamera)];
/*UIBarButtonItem *flexItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:nil
action:nil];*/
//UIBarButtonItem *infoButton = [[UIBarButtonItem alloc] initWithTitle:#" Info " style:UIBarButtonItemStyleBordered target:self action:#selector(infoButton)];
/*UIButton *info = [UIButton buttonWithType:UIButtonTypeInfoLight];
[info addTarget:self action:#selector(infoButton) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *infoButton = [[UIBarButtonItem alloc] initWithCustomView:info];
[bottomBar setItems:[NSArray arrayWithObjects:cancel,flexItem,infoButton, nil]];*/
[bottomBar setItems:[NSArray arrayWithObjects:cancel, nil]];
[ovlView addSubview:leftBracket];
[ovlView addSubview:rightBracket];
[ovlView addSubview:bottomBar];
reader.cameraOverlayView = ovlView;
// present and release the controller
[self presentModalViewController:reader
animated: YES];
[reader release];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UIView * previewView = [[[[[[[[[[
reader.view // UILayoutContainerView
subviews] objectAtIndex:0] // UINavigationTransitionView
subviews] objectAtIndex:0] // UIViewControllerWrapperView
subviews] objectAtIndex:0] // UIView
subviews] objectAtIndex:0] // PLCameraView
subviews] objectAtIndex:0]; // PLPreviewView
[previewView touchesBegan:touches withEvent:event];
}
Thanks for MacN00b's answer! That points out the right direction to go for me. I have implemented tap-focus for zbarViewController. Here is the idea:
You can add a custom view to zbarViewController by assigning a custom view to its cameraOverlayView. Then add a TapGestureRecagonizer to the custom view to catch the tap. Then, get the touch point and make the camera focus to the touch point. You would like possibly add a little rectangle around the touch point(that is what I did).
Here goes the code(assigning the custom view to cameraOverlayView:
UIView *view = [[UIView alloc] init];
UITapGestureRecognizer* tapScanner = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(focusAtPoint:)];
[view addGestureRecognizer:tapScanner];
reader.cameraOverlayView = view;
Then in selector focusAtPoint:
- (void)focusAtPoint:(id) sender{
CGPoint touchPoint = [(UITapGestureRecognizer*)sender locationInView:_reader.cameraOverlayView];
double focus_x = touchPoint.x/_reader.cameraOverlayView.frame.size.width;
double focus_y = (touchPoint.y+66)/_reader.cameraOverlayView.frame.size.height;
NSError *error;
NSArray *devices = [AVCaptureDevice devices];
for (AVCaptureDevice *device in devices){
NSLog(#"Device name: %#", [device localizedName]);
if ([device hasMediaType:AVMediaTypeVideo]) {
if ([device position] == AVCaptureDevicePositionBack) {
NSLog(#"Device position : back");
CGPoint point = CGPointMake(focus_y, 1-focus_x);
if ([device isFocusModeSupported:AVCaptureFocusModeContinuousAutoFocus] && [device lockForConfiguration:&error]){
[device setFocusPointOfInterest:point];
CGRect rect = CGRectMake(touchPoint.x-30, touchPoint.y-30, 60, 60);
UIView *focusRect = [[UIView alloc] initWithFrame:rect];
focusRect.layer.borderColor = [UIColor whiteColor].CGColor;
focusRect.layer.borderWidth = 2;
focusRect.tag = 99;
[_reader.cameraOverlayView addSubview:focusRect];
[NSTimer scheduledTimerWithTimeInterval: 1
target: self
selector: #selector(dismissFocusRect)
userInfo: nil
repeats: NO];
[device setFocusMode:AVCaptureFocusModeAutoFocus];
[device unlockForConfiguration];
}
}
}
}
}
I have added a white rectangle around the touch point, and then use selector dismissFocusRect to dismiss this rectangle. Here is the code:
- (void) dismissFocusRect{
for (UIView *subView in _reader.cameraOverlayView.subviews)
{
if (subView.tag == 99)
{
[subView removeFromSuperview];
}
}
}
I hope this could help!
Look at this documentation by apple in the "Focus Modes" section: https://developer.apple.com/library/ios/#documentation/AudioVideo/Conceptual/AVFoundationPG/Articles/04_MediaCapture.html It talks all about how to implement tap to focus properly. I would try to implement this by
CGRect screenRect = [[UIScreen mainScreen] bounds];
screenWidth = screenRect.size.width;
screenHeight = screenRect.size.height;
double focus_x = thisFocusPoint.center.x/screenWidth;
double focus_y = thisFocusPoint.center.y/screenHeight;
[[self captureManager].videoDevice lockForConfiguration:&error];
[[self captureManager].videoDevice setFocusPointOfInterest:CGPointMake(focus_x,focus_y)];
Well if you are using that view controller, how about adding a (void) that should be ok to implement in the barcodeviewcontroller.
- (void) focusAtPoint:(CGPoint)point
{
AVCaptureDevice *device = [[self videoInput] device];
if ([device isFocusPointOfInterestSupported] && [device isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
NSError *error;
if ([device lockForConfiguration:&error]) {
[device setFocusPointOfInterest:point];
[device setFocusMode:AVCaptureFocusModeAutoFocus];
[device unlockForConfiguration];
} else {
id delegate = [self delegate];
if ([delegate respondsToSelector:#selector(acquiringDeviceLockFailedWithError:)]) {
[delegate acquiringDeviceLockFailedWithError:error];
}
}
}
}

How do I remove or stop a button in table view from working after registered amount of taps

I have a button in a table view that adds rows. After a maximum of five rows I want to stop the user adding anymore. Currently I show an alert after button recives 5 taps.
How can I stop the user from using the button past this point? Setting to hidden wont work as its a custom subclass and property hidden is not found on the class
- (void)viewDidLoad
{
[super viewDidLoad];
UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
titleLabel.backgroundColor = [UIColor clearColor];
titleLabel.textColor = [UIColor whiteColor];
titleLabel.shadowColor = [UIColor darkGrayColor];
titleLabel.text = self.distributionBoard.dbRef;
titleLabel.font = [UIFont boldSystemFontOfSize:15.0f];
[titleLabel sizeToFit];
self.navigationItem.titleView = titleLabel;
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(doneButtonPressed:)];
// Add new appliance button to the table view's footer view
UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(10.0f, 0, 300.0f, 100.0f)];
footerView.backgroundColor = [UIColor clearColor];
UIButton *newBoardButton = [UIButton buttonWithType:UIButtonTypeContactAdd];
CGRect buttonFrame = newBoardButton.frame;
buttonFrame.origin.x = footerView.frame.size.width - buttonFrame.size.width;
newBoardButton.frame = buttonFrame;
[newBoardButton addTarget:self action:#selector(addCircuitButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[footerView addSubview:newBoardButton];
self.tableView.tableFooterView = footerView;
}
.....
////limit to five appliances
- (void)addCircuitButtonPressed:(id)sender {
LogCmd();
Circuit *circuit = [[ICCircuitManager manager] newCircuit];
circuit.distributionBoard = self.distributionBoard;
circuit.circuitReference = [NSString stringWithFormat:#"%d", [self.circuits count] + 1];
circuit.createdAt = [NSDate date];
circuit.modifiedAt = [NSDate date];
[self.distributionBoard addCircuitsObject:circuit];
[self loadData];
[self.tableView reloadData];
{
m_buttonTouchCount++;
if ( m_buttonTouchCount == 4)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"iCertifi"
message:#"Maximum number of appliances reached"
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alert show];
// m_buttonTouchCount = 0; // reset to 0 here if required.
}
}
}
Where you have AlertView you can type this code to disable button:
[(UIButton *)sender setEnabled:NO];
or to hide button:
[(UIButton *)sender setHidden:YES];

How to add clickable Links to UILabel with attributedText in iOS 6

I used DTCoreText to display formatted text in my apps. DTAttributedTextView also supports clickable links.
Since iOS6 we can use the setAttributedText function to display attributedStrings in UILabel.
But how can I display Links that are clickable? Is there a way to call a delegate Function etc. when a link is pressed?
The iOS 6.0 UILabel still cant display clickable links.
However you could use a UITextView instead. The textview can detect links, but the link detection only work if editing of text is disabled. Limitations are that you cant do something like this in BBCode [url=www.apple.com]Apples Website[/url].
Here is example code to hyperlink UILabel:
Source:http://sickprogrammersarea.blogspot.in/2014/03/adding-links-to-uilabel.html
#import "ViewController.h"
#import "TTTAttributedLabel.h"
#interface ViewController ()
#end
#implementation ViewController
{
UITextField *loc;
TTTAttributedLabel *data;
}
- (void)viewDidLoad
{
[super viewDidLoad];
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(5, 20, 80, 25) ];
[lbl setText:#"Text:"];
[lbl setFont:[UIFont fontWithName:#"Verdana" size:16]];
[lbl setTextColor:[UIColor grayColor]];
loc=[[UITextField alloc] initWithFrame:CGRectMake(4, 20, 300, 30)];
//loc.backgroundColor = [UIColor grayColor];
loc.borderStyle=UITextBorderStyleRoundedRect;
loc.clearButtonMode=UITextFieldViewModeWhileEditing;
//[loc setText:#"Enter Location"];
loc.clearsOnInsertion = YES;
loc.leftView=lbl;
loc.leftViewMode=UITextFieldViewModeAlways;
[loc setDelegate:self];
[self.view addSubview:loc];
[loc setRightViewMode:UITextFieldViewModeAlways];
CGRect frameimg = CGRectMake(110, 70, 70,30);
UIButton *srchButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
srchButton.frame=frameimg;
[srchButton setTitle:#"Go" forState:UIControlStateNormal];
[srchButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
srchButton.backgroundColor=[UIColor clearColor];
[srchButton addTarget:self action:#selector(go:) forControlEvents:UIControlEventTouchDown];
[self.view addSubview:srchButton];
data = [[TTTAttributedLabel alloc] initWithFrame:CGRectMake(5, 120,self.view.frame.size.width,200) ];
[data setFont:[UIFont fontWithName:#"Verdana" size:16]];
[data setTextColor:[UIColor blackColor]];
data.numberOfLines=0;
data.delegate = self;
data.enabledTextCheckingTypes=NSTextCheckingTypeLink|NSTextCheckingTypePhoneNumber;
[self.view addSubview:data];
}
- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url
{
NSString *val=[[NSString alloc]initWithFormat:#"%#",url];
if ([[url scheme] hasPrefix:#"mailto"]) {
NSLog(#" mail URL Selected : %#",url);
MFMailComposeViewController *comp=[[MFMailComposeViewController alloc]init];
[comp setMailComposeDelegate:self];
if([MFMailComposeViewController canSendMail])
{
NSString *recp=[[val substringToIndex:[val length]] substringFromIndex:7];
NSLog(#"Recept : %#",recp);
[comp setToRecipients:[NSArray arrayWithObjects:recp, nil]];
[comp setSubject:#"From my app"];
[comp setMessageBody:#"Hello bro" isHTML:NO];
[comp setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
[self presentViewController:comp animated:YES completion:nil];
}
}
else{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:val]];
}
}
-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{
if(error)
{
UIAlertView *alrt=[[UIAlertView alloc]initWithTitle:#"Erorr" message:#"Some error occureed" delegate:nil cancelButtonTitle:#"" otherButtonTitles:nil, nil];
[alrt show];
[self dismissViewControllerAnimated:YES completion:nil];
}
else{
[self dismissViewControllerAnimated:YES completion:nil];
}
}
- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithPhoneNumber:(NSString *)phoneNumber
{
NSLog(#"Phone Number Selected : %#",phoneNumber);
UIDevice *device = [UIDevice currentDevice];
if ([[device model] isEqualToString:#"iPhone"] ) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:#"tel:%#",phoneNumber]]];
} else {
UIAlertView *Notpermitted=[[UIAlertView alloc] initWithTitle:#"Alert" message:#"Your device doesn't support this feature." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[Notpermitted show];
}
}
-(void)go:(id)sender
{
[data setText:loc.text];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(#"Reached");
[loc resignFirstResponder];
}