Change color NavigationBar in detail screen CNContactPickerViewController - objective-c

I have a problem like in this question, but answers don't help me. I want that colors navigation bar in seconds screen will be like a first screen. iOS 9 or later.
- (void) showAdressBookActionForIOSNineOrLater {
CNContactPickerViewController * newPicker = [[CNContactPickerViewController alloc] init];
newPicker.delegate = self;
NSDictionary *attributesNormal = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont appFont_Headline], NSFontAttributeName,
[UIColor appColor_white_0], NSForegroundColorAttributeName, nil];
//appColor_white_0 my custom color APP_RGBA(255.0f, 255.0f, 255.0f, 1.0f); appFont_Headline - [UIFont HelveticaNeueRegularFont:fontSize];
newPicker.navigationController.navigationBar.titleTextAttributes = attributesNormal;
newPicker.navigationController.navigationBar.translucent = NO;
newPicker.navigationController.navigationBar.barStyle = UIBarStyleBlack;
newPicker.navigationController.navigationBar.tintColor = [UIColor appColor_white_0];
[[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:#[[UINavigationController class]]] setTintColor:[UIColor appColor_white_0]];
[[UINavigationBar appearanceWhenContainedInInstancesOfClasses:#[[UINavigationController class]]] setTintColor:[UIColor appColor_white_0]];
[[UINavigationBar appearanceWhenContainedInInstancesOfClasses:#[[UINavigationController class]]] setBarTintColor:[UIColor appColor_white_0]];
[[UINavigationBar appearanceWhenContainedInInstancesOfClasses:#[[UINavigationController class]]] setTitleTextAttributes:attributesNormal];
newPicker.predicateForEnablingContact = [NSPredicate predicateWithFormat:#"phoneNumbers.#count > 0"];
newPicker.predicateForSelectionOfContact = [NSPredicate predicateWithFormat:#"phoneNumbers.#count == 1"];
newPicker.predicateForSelectionOfProperty = [NSPredicate predicateWithFormat:#"key == phoneNumber"];
newPicker.displayedPropertyKeys = #[CNContactPhoneNumbersKey];
//
[[self currentNavigationController] presentViewController:newPicker animated:YES completion:nil];
And implement delegate methods:
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperty:(CNContactProperty *)contactProperty{
CNContact *contact = contactProperty.contact;
NSString *identify = contactProperty.identifier;
NSString * selectedNumber = #"";
for (CNLabeledValue<CNPhoneNumber*>* number in contact.phoneNumbers) {
if ([number.identifier isEqualToString:identify]) {
selectedNumber = ((CNPhoneNumber *)number.value).stringValue;
}
} [self.currentNavigationController.presentedViewController dismissViewControllerAnimated:YES completion:nil];
}
- (void)contactPickerDidCancel:(CNContactPickerViewController *)picker {
[self.currentNavigationController.presentedViewController dismissViewControllerAnimated:YES completion:nil];
}
Screen story:

Related

How to optimize UITextView

I use UITextView as the rich text view
- (void)openPhotoLibrary {
[self presentImagePickerController:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (void)presentImagePickerController:(UIImagePickerControllerSourceType)sourceType {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.sourceType = sourceType;
[self presentViewController:picker animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
[picker dismissViewControllerAnimated:YES completion:nil];
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *dataImage = UIImageJPEGRepresentation(image, 0.1);
UIImage *resultImage = [UIImage imageWithData:dataImage];
[self insertImageOfTheTextView:self.textview withImage:resultImage];
[picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)insertImageOfTheTextView:(UITextView *)textView withImage:(UIImage *)image {
if (image == nil || ![image isKindOfClass:[UIImage class]]) {
return;
}
NImageAttachment *attachment = [[NImageAttachment alloc] init];
attachment.image = image;
attachment.imageSize = [self scaleImageSize:image];
NSAttributedString *imageAttributedString = [self insertImageDoneAutoReturn:[NSAttributedString attributedStringWithAttachment:attachment]];
[textView.textStorage insertAttributedString:imageAttributedString atIndex:textView.selectedRange.location];
textView.selectedRange = NSMakeRange(textView.selectedRange.location + 3, 0);
}
- (CGSize)scaleImageSize:(UIImage *)image {
CGFloat imageScale = image.size.width / image.size.height;
CGFloat imageWidth = self.view.frame.size.width;
CGSize imageSize = CGSizeMake(imageWidth, imageWidth / imageScale);
return imageSize;
}
- (NSAttributedString *)insertImageDoneAutoReturn:(NSAttributedString *)imageAttributedString {
NSAttributedString *returnAttributedString = [[NSAttributedString alloc] initWithString:#"\n"];
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:imageAttributedString];
[attributedString appendAttributedString:returnAttributedString];
[attributedString insertAttributedString:returnAttributedString atIndex:0];
return attributedString;
}
If the photo I picked from PhotoLibrary is small, the uitextivew will be fine, if the photo is large, the uitextview will be slow when I scroll or edit the uitextview, it seems stucks, how can I optimize it?

UIButtons in UIScrollView stop working after 3 rows

I have a UIScrollView with a list of UIViews within it. Bit like a fancy tableview. One issue I am having is the buttons work ok for the first 3 'rows' in the scrollview, but none of the buttons after this respond when i scroll down. Looks like its working ok for the buttons that show on screen when the view has loaded but anything further down when i scroll will now respond at all...
code from within the uiview repeated within uiscrollview
-(void)addButtons
{
UIButton *visiteWebSite = [UIButton buttonWithType:UIButtonTypeCustom];
[visiteWebSite addTarget:self
action:#selector(visitSite:)
forControlEvents:UIControlEventTouchDown];
[visiteWebSite setTintColor:[UIColor colorWithRed:247 green:143 blue:30 alpha:1.0]];
visiteWebSite.frame = CGRectMake(440.0, 10.0, 120.0, 26.0);
if(![self IsPhone5]) {
visiteWebSite.frame = CGRectMake(350.0, 10.0, 120.0, 26.0);
}
//visiteWebSite.backgroundColor = [UIColor orangeColor]; //[UIColor colorWithRed:247 green:143 blue:30 alpha:1.0];
[visiteWebSite setBackgroundImage:[UIImage imageNamed:#"orangeBG"] forState:UIControlStateNormal];
[visiteWebSite setTitle:#"VISITE WEBSITE" forState:UIControlStateNormal];
visiteWebSite.titleLabel.font = [UIFont fontWithName:#"arial" size:12];
[self addSubview:visiteWebSite];
UIButton *getDirections = [UIButton buttonWithType:UIButtonTypeCustom];
[getDirections addTarget:self
action:#selector(getDirections:)
forControlEvents:UIControlEventTouchDown];
[getDirections setTitle:#"GET DIRECTIONS" forState:UIControlStateNormal];
getDirections.titleLabel.font = [UIFont fontWithName:#"arial" size:12];
getDirections.frame = CGRectMake(440.0, 46.0, 120.0, 26.0);
if(![self IsPhone5]) {
getDirections.frame = CGRectMake(350.0, 46.0, 120.0, 26.0);
}
[getDirections setBackgroundImage:[UIImage imageNamed:#"orangeBG"] forState:UIControlStateNormal];
[self addSubview:getDirections];
}
Code from Parent View containing the UIScrollView
-(void)performSearch
{
[self.loadinglabel removeFromSuperview];
NSString* searchTerm = txtSearch.text;
searchTerm = [searchTerm stringByReplacingOccurrencesOfString:#" " withString:#""];
NSData *urldata = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.collectioncosmetics.co.uk/storelocatorapi?store=%#",searchTerm]]];
NSString *json = [[NSString alloc] initWithData:urldata encoding:NSUTF8StringEncoding];
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
NSArray *jsonObjects = [jsonParser objectWithString:json];
float y = 0;
float height = 84;
if([jsonObjects count] < 1) {
UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:#"NO RESULTS" message:#"There are no stores near the postcode you searched" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alertView show];
[self back:nil];
return;
}
for (int i = 0; i < [jsonObjects count]; i++)
{
NSDictionary *dict = [jsonObjects objectAtIndex:i];
CARStoreResult* result = [[CARStoreResult alloc] initWithFrame:CGRectMake(0, height*i, tv.frame.size.width, height)];
result.name = [dict objectForKey:#"name"];
result.street = [dict objectForKey:#"street"];
result.area = [dict objectForKey:#"area"];
result.county = [dict objectForKey:#"County"];
result.postcode = [dict objectForKey:#"PostCode"];
result.distance = [dict objectForKey:#"distance"];
result.usersPostCode = searchTerm;
result.y = y;
result.num = i;
y = y + height;
[result build];
[tv addSubview:result];
}
[tv setFrame:CGRectMake(tv.frame.origin.x, tv.frame.origin.y, tv.frame.size.width, height*[jsonObjects count])];
[self.scrollView setContentSize:tv.frame.size];
[Flurry logEvent:#"Store Locator"];
}
FIXED!
instead of adding the views to a view within the scrollview i added them just directly to the scrollview. with the scrollview having scrollView.canCancelContentTouches set to NO.
//[tv addSubview:result];
[self.scrollView addSubview:result];
}
//[tv setFrame:CGRectMake(tv.frame.origin.x, tv.frame.origin.y, tv.frame.size.width, height*[jsonObjects count])];
[self.scrollView setContentSize:CGSizeMake(320, height*[jsonObjects count])];
//[self.scrollView setContentSize:tv.frame.size];
[Flurry logEvent:#"Store Locator"];

UITabbarItem BadgeValue Text Color

I have a problem in my App. I set a badge value at one of the tabs in the UITabBar. The Badge value is correctly red and the circle around the badge value is correctly in white. The problem is, that the color of the text is gray (160, 160, 160). It is the same color like the normal state tabbaritem text is, but I set this color nowhere in the app code and I do not know where this color come from.
I searched for that issue in the whole net since weeks but I cannot find any solution. The only answer I found everywhere is, that it is not possible to change the color of the text of the badge value. But if it is not possible, why is it changed in my app?
I hope, that somebody can help me with that issue...
http://www.luventas-webdesign.de/stackoverflow/screenshot_badgevalue.png
Like the color is in my app
http://www.luventas-webdesign.de/stackoverflow/screenshot_like_it_should.png
Like the color should normally be...
Edit 02.11.2012 - Code
Creation of TabBarController:
#import "ExtendedTabBarController.h"
#import "configuration.h"
#implementation ExtendedTabBarController
- (void)viewDidLoad {
[super viewDidLoad];
[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIColor colorWithRed:207.0/255.0 green:70.0/255.0 blue:61.0/255.0 alpha:1], UITextAttributeTextColor, [UIFont fontWithName:#"KievitPro-Regular" size:10.0], UITextAttributeFont, nil] forState:UIControlStateSelected];
[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIColor colorWithRed:255.0/255.0 green:255.0/255.0 blue:255.0/255.0 alpha:1], UITextAttributeTextColor, [UIFont fontWithName:#"KievitPro-Regular" size:10.0], UITextAttributeFont, nil] forState:UIControlStateNormal];
[self.tabBar sizeToFit];
UIView *tabbarBackgroundColorView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0, self.view.bounds.size.width, 49)];
[tabbarBackgroundColorView setBackgroundColor:[UIColor colorWithRed:233.0/255.0 green:233.0/255.0 blue:233.0/255.0 alpha:1]];
[self.tabBar insertSubview:tabbarBackgroundColorView atIndex:0];
}
- (void)viewDidUnload {
[super viewDidUnload];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return UIInterfaceOrientationIsPortrait(interfaceOrientation); // only portrait orientation
}
/**
* orientation for iOS6
**/
-(NSUInteger)supportedInterfaceOrientations{
return UIInterfaceOrientationMaskPortrait;
}
#end
Call in AppDelegate:
ExtendedTabBarController *tabBarController = [[ExtendedTabBarController alloc] init];
[self setTabBarController:tabBarController];
[[UITabBar appearance] setBackgroundImage:[UIImage imageNamed:#"menu_bg"]];
// code for initialize View- and NavigationControllers...
self.tabBarController.viewControllers = #[highlightsNavigationController, categoryNavigationController, searchNavigationController, favoritesNavigationController, imprintNavigationController];
self.window.rootViewController = self.tabBarController;
[[UITabBar appearance] setSelectionIndicatorImage:[[UIImage alloc] init]];
Set the badge value:
int viewCount = 0;
NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
NSDictionary * dict = [defs dictionaryRepresentation];
for (id key in dict) {
if([key rangeOfString:#"_highlighted"].location != NSNotFound && [[[dict objectForKey:key] objectAtIndex:0] isEqualToString:#"YES"]) {
viewCount++;
}
}
UITabBarItem *tbi = (UITabBarItem *)[self.tabBarController.tabBar.items objectAtIndex:3];
if(viewCount <= 0) {
tbi.badgeValue = nil;
} else {
tbi.badgeValue = nil;
tbi.badgeValue = [NSString stringWithFormat:#"%d", viewCount];
}
Code for overwritten UILabel:
// -- file: UILabel+VerticalAlign.h
#pragma mark VerticalAlign
#interface UILabel (VerticalAlign)
- (void)alignTop;
- (void)alignBottom;
- (void)awakeFromNib;
-(id)initWithFrame:(CGRect)frame;
#end
#import "UILabel+VerticalAlign.h"
// -- file: UILabel+VerticalAlign.m
#implementation UILabel (VerticalAlign)
- (void)alignTop {
CGSize fontSize = [self.text sizeWithFont:self.font];
double finalHeight = fontSize.height * self.numberOfLines;
double finalWidth = self.frame.size.width; //expected width of label
CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];
int newLinesToPad = (finalHeight - theStringSize.height) / fontSize.height;
for(int i=0; i<newLinesToPad; i++)
self.text = [self.text stringByAppendingString:#"\n "];
}
- (void)alignBottom {
CGSize fontSize = [self.text sizeWithFont:self.font];
double finalHeight = fontSize.height * self.numberOfLines;
double finalWidth = self.frame.size.width; //expected width of label
CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];
int newLinesToPad = (finalHeight - theStringSize.height) / fontSize.height;
for(int i=0; i<newLinesToPad; i++)
self.text = [NSString stringWithFormat:#" \n%#",self.text];
}
- (void)awakeFromNib
{
[super awakeFromNib];
[self setFont:[UIFont fontWithName:#"KievitPro-Regular" size:12.0]];
}
-(id)initWithFrame:(CGRect)frame
{
id result = [super initWithFrame:frame];
if (result) {
[self setFont:[UIFont fontWithName:#"KievitPro-Regular" size:12.0]];
}
return result;
}
#end
I found a solution for my problem on my own:
I must remove the following lines from the overwritten UILabel:
- (void)awakeFromNib
{
[super awakeFromNib];
[self setFont:[UIFont fontWithName:#"KievitPro-Regular" size:12.0]];
}
-(id)initWithFrame:(CGRect)frame
{
id result = [super initWithFrame:frame];
if (result) {
[self setFont:[UIFont fontWithName:#"KievitPro-Regular" size:12.0]];
}
return result;
}
Maybe someone can explain me, why this lines change the text color of the badge value, before we can close this post?
Instead of setting the default UILabel font using a category, use the UILabel's appearance method to set the font:
[[UILabel appearance] setFont:[UIFont fontWithName:#"KievitPro-Regular" size:12.0]];
When I tested this the text for the badge appeared as the normal white color.

Couldn't change the orientation in SplitViewController

I am not much familiar with iPad app SplitViewController. I have used the SplitViewController in my app. When change the orientation from portrait to landscape, Masterview is hiding from splitView. Could you please any help me to sort out this issue.
I have attached my source for your reference.
Creating SplitViewController:
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
menuViewController = [[MainMenuViewController alloc] initWithNibName:#"MainMenuViewController" bundle:nil];
UINavigationController *masterNavigationController = [[UINavigationController alloc] initWithRootViewController:menuViewController] ;
masterNavigationController.navigationBar.barStyle = UIBarStyleBlack;
MainMenuDetailViewController *detailViewController = [[MainMenuDetailViewController alloc] initWithNibName:#"MainMenuDetailViewController" bundle:nil] ;
UINavigationController *detailNavigationController = [[UINavigationController alloc] initWithRootViewController:detailViewController] ;
detailNavigationController.navigationBar.barStyle = UIBarStyleBlack;
self.splitViewController = [[UISplitViewController alloc] init];
[self.splitViewController.view setBackgroundColor:[UIColor whiteColor]];
self.splitViewController.delegate = detailViewController;
self.splitViewController.viewControllers = [NSArray arrayWithObjects:masterNavigationController, detailNavigationController, nil];
DetailView Page:
pragma mark -
pragma mark Split view support
(void)splitViewController: (UISplitViewController*)svc willHideViewController:(UIViewController )aViewController withBarButtonItem:(UIBarButtonItem)barButtonItem forPopoverController: (UIPopoverController*)pc {
barButtonItem.title = NSLocalizedString(#"Menu", #"Menu");
[self.navigationItem setLeftBarButtonItem:barButtonItem animated:YES];
self.masterPopoverController = pc;
appDelegate.rootPopoverButtonItem = barButtonItem;
appDelegate.masterPopoverController = pc;
}
// Called when the view is shown again in the split view, invalidating the button and popover controller.
- (void)splitViewController: (UISplitViewController*)svc willShowViewController:(UIViewController *)aViewController invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem {
[self.navigationItem setLeftBarButtonItem:nil animated:YES];
self.masterPopoverController = nil;
}
MasterView Button Tap:
[appDelegate.splitViewController viewWillDisappear:YES];
[UIView beginAnimations: #"Showinfo"context: nil];
[UIView setAnimationCurve: UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:0.5];
NSMutableArray *viewControllerArray=[[NSMutableArray alloc] initWithArray:[[appDelegate.splitViewController.viewControllers objectAtIndex:1] viewControllers]];
[viewControllerArray removeLastObject];
if( viewMenu.hidden == YES) // Main Menu
{
if(btnMenu.tag == 1) // Service Report Form
{
if (!self.mainMenuDetailViewController) {
self.mainMenuDetailViewController = [[MainMenuDetailViewController alloc] initWithNibName:#"MainMenuDetailViewController" bundle:nil];
}
[viewControllerArray addObject:self.mainMenuDetailViewController];
appDelegate.splitViewController.delegate = self.mainMenuDetailViewController;
}
if(btnMenu.tag == 4) // Signout
{
[self.navigationItem setLeftBarButtonItem:nil];
[appDelegate SignOut];
btnSignOut.frame = CGRectMake(24,275,272,50);
}
else if(btnMenu.tag == 2) // Inquiries
{
if (!self.inquiryViewController) {
self.inquiryViewController = [[InquiryViewController alloc] initWithNibName:#"InquiryViewController" bundle:nil] ;
}
[viewControllerArray addObject:self.inquiryViewController];
appDelegate.splitViewController.delegate = self.inquiryViewController;
}
else if(btnMenu.tag == PageMasterSync)
{
if (!self.mastSyncViewController) {
self.mastSyncViewController = [[MastSyncViewController alloc] initWithNibName:#"MastSyncViewController" bundle:nil] ;
}
appDelegate.splitViewController.delegate = self.mastSyncViewController;
[viewControllerArray addObject:self.mastSyncViewController];
}
else if(btnMenu.tag == PageServiceReport)
{
if(!self.srListViewController)
self.srListViewController = [[SRListViewController alloc] initWithNibName:#"SRListViewController" bundle:nil];
appDelegate.splitViewController.delegate = srListViewController;
[viewControllerArray addObject:self.srListViewController];
}
}
}
[[appDelegate.splitViewController.viewControllers objectAtIndex:1] setViewControllers:viewControllerArray animated:NO];
if(btnMenu.tag == PageReview && !viewMenu.hidden)
[self.reviewViewController loadServiceReport];
[appDelegate.splitViewController viewWillAppear:YES];
[viewControllerArray release];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.view cache:NO];
[UIView commitAnimations];
With regards
Senthil

UIPickerView with a Done button in Ipad

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;
}
}