UIActionSheet with an Image - ios

For God's sake somebody tell me how to add a picture on an UIActionSheet.
I am adding it, but can't force the sheet to restretch its height, so the Subview would fit.
var sheet = new UIActionSheet ("Sheet with a picture");
sheet.AddButton ("Pick New Picture");
var subView = new UIView(new RectangleF(20,100,280,200)){
BackgroundColor = UIColor.FromPatternImage(Picture)};
sheet.AddSubview(subView);
sheet.AddButton ("Cancel");
sheet.CancelButtonIndex = 1;
I've tried to change contentMode of subView and the sheet. Didn't work. What am I doing wrong?
Picture should fit between buttons, or fit on the sheet somehow through any other way around

I know this sounds really stupid, but the easiest solution I found is to add a few dummy buttons (to preserve space) and then on top of them add the UIImageView accurately defining the frame coordinates.
var sheet = new UIActionSheet ("");
sheet.AddButton ("Discard Picture");
sheet.AddButton ("Pick New Picture");
sheet.AddButton ("Cancel");
sheet.CancelButtonIndex = 2;
// Dummy buttons to preserve the space for the UIImageView
for (int i = 0; i < 4; i++) {
sheet.AddButton("");
sheet.Subviews[i+4].Alpha = 0; // And of course it's better to hide them
}
var subView = new UIImageView(Picture);
subView.ContentMode = UIViewContentMode.ScaleAspectFill;
subView.Frame = new RectangleF(23,185,275,210);
// Late Steve Jobs loved rounded corners. Let's have some respect for him
subView.Layer.CornerRadius = 10;
subView.Layer.MasksToBounds = true;
subView.Layer.BorderColor = UIColor.Black.CGColor;
sheet.AddSubview(subView);

UIActionSheet doesn't support customization of this type. You can subclass UIActionSheet and muck with the default layout (override layoutSubviews, call the super implementation, then move things around). If you do this, there's no guarantee your sublcass will work in future versions of iOS if Apple changes the framework implementation.
The other alternative is to find or implement an alternative class that does what you want.

Actually it is quite easy and you don't need a hack:
Change the size of the UIActionSheet AFTER calling showInView (or showFromTabBar, etc), like they do in this example.
You might have to change the Frame instead of the Bounds, in my experience the action sheet is not moved to the right position if you change the Bounds.
On the iPad this doesn't work unfortunately. But there you can use a UIPopoverController. (Tip: you can use 0 for the UIPopoverArrowDirection if you do not want arrows).

This is Agzam's answer, but refreshed for most recent objc and without the background button hack, as suggested by Marcel W. it is shorter and possibly cleaner.
UIActionSheet *actionSheet = [[UIActionSheet alloc] init];
actionSheet.actionSheetStyle = UIActionSheetStyleAutomatic;
actionSheet.title = #"some text";//here type your information text
actionSheet.delegate = self;
[actionSheet addButtonWithTitle:#"Button 1"];
[actionSheet addButtonWithTitle:#"Button 2"];
[actionSheet setCancelButtonIndex:1];
//it is up to you how you show it, I like the tabbar
[actionSheet showFromTabBar:self.tabBarController.tabBar];
//here lays the trick - you change the size after you've called show
[actionSheet setBounds:CGRectMake(0,0,320, 480)];
//now create and add your image
UIImageView *subView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"exampleimage.png"]];
subView.ContentMode = UIViewContentModeScaleAspectFit;
subView.Frame = CGRectMake(0,130,320,180);//adjust these, so that your text fits in
[actionSheet addSubview: (subView)];
[subView release];
[actionSheet release];

Related

How to change top margin for UIBarButtonItem

I have a toolbar in my view. it contains a Bar button item with an icon, actually it's not an icon (it's a custom font). I'm using it to unify the icons with other web application for the same customer.
Anyway, how could I increase the top margin a little bit ... maybe the given example is showing a filter icon that I can easily replace it with real image icon (not a font). But some other icons, it's impossible.
Edit 1:
I'm using C# (Xamarin). Even if there is an object-c code. I'm ok with it.
var att = new UITextAttributes ();
att.Font = FontHelper.GetIconFont (32.0f);
this.btnFilter.SetTitleTextAttributes (att, UIControlState.Normal);
the custom icon font method:
public static UIFont GetIconFont(float size)
{
var nfloatSize = nfloat.Parse (((float)size).ToString ());
return UIFont.FromName(_fontIcons, nfloatSize);
}
Try something like this,
float offset = 3.0f;
UIBarButtonItem * barItem = [[UIBarButtonItem alloc] initWithTitle:#"title"
style:UIBarButtonItemStyleDone
target:nil action:#selector(someMessage)];
[barItem setBackgroundVerticalPositionAdjustment:offset forBarMetrics:UIBarMetricsDefault];
I'm thinking of the way of doing subclass UINavigationBar and override layoutSubviews and reposition the UIBarButtonItem. Also, don't forget to set UINavigationBar class to UINavigationBar subclass in Interface Builder. So you may try something like this:
// UINavigationBar subclass
#define NAVIGATION_MARGIN 3
#implementation NewNavigationBar
- (void)layoutSubviews {
[super layoutSubviews];
UINavigationItem *navigationItem = [self topItem];
subview = [[navigationItem leftBarButtonItem] customView];
if (subview) {
CGRect subviewFrame = subview.frame;
subview.frame.origin.x = NAVIGATION_BTN_MARGIN;
subview.frame.origin.y = (self.frame.size.height - subview.frame.size.height) / 2;
[subview setFrame:subviewFrame];
}
}
#end
I'm not sure what language your working in but use the backgroundVerticalPositionAdjustment property of UIBarButtonItem.
button.setBackgroundVerticalPositionAdjustment(3.0, forBarMetrics: .Default)
When using text / Ionicons, the following is what's needed to reposition the icon ( Xamarin code below ):
button.SetTitlePositionAdjustment(
new UIOffset() { Vertical = 15.0f, Horizontal = 5.0f },
UIBarMetrics.Default );

UIAlertView addSubview in iOS7

Adding some controls to UIAlertView was deprecated in iOS7 using addSubview method. As I know Apple promised to add contentView property.
iOS 7 is released now and I see that this property is not added. That is why I search for some custom solution with ability to add progress bar to this alertView. Something for example similar to TSAlertView, but more ready for using in iOS 7.
Here is a project on Github to add any UIView to an UIAlertView-looking dialog on iOS7.
(Copied from this StackOverflow thread.)
It took me only 1 day to create my own alert view that looks exactly like Apple's
Take a screenshot of Apple's alert for reference (font sizes, spacings, width)
Create a xib with title, message, custom view and tables for buttons (Apple uses tables instead of UIButton now, default table cell is good enough). Note you need 3 button tables: two for left and right buttons (whenever the number of buttons is 2), another one for the other cases (one button or more than 2 buttons).
Implement all the methods from UIAlertView on your custom alert.
Show/Dismiss - you can create a specific modal window for your alerts but I just put my alerts on top of my root view controller. Register your visible alerts to a static array. If showing the first alert/dismissing the last, change tint mode of your window/view controller to dimmed/to automatic and add/remove a dimming view (black with alpha = 0.2).
Blurred background - use Apple's sample code (I used opaque white)
3D dynamic effects - use Apple's sample code (5 lines of code). If you want a nice effect, take a slightly bigger snapshot in step 5 and add inverse animators for alert background and foreground.
EDIT:
Both blurred background and the paralax effect sample code can be found in "iOS_RunningWithASnap" WWDC 2013 sample code
Paralax effect:
UIInterpolatingMotionEffect* xAxis = [[[UIInterpolatingMotionEffect alloc] initWithKeyPath:#"center.x"
type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis] autorelease];
xAxis.minimumRelativeValue = [NSNumber numberWithFloat:-10.0];
xAxis.maximumRelativeValue = [NSNumber numberWithFloat:10.0];
UIInterpolatingMotionEffect* yAxis = [[[UIInterpolatingMotionEffect alloc] initWithKeyPath:#"center.y"
type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis] autorelease];
yAxis.minimumRelativeValue = [NSNumber numberWithFloat:-10.0];
yAxis.maximumRelativeValue = [NSNumber numberWithFloat:10.0];
UIMotionEffectGroup *group = [[[UIMotionEffectGroup alloc] init] autorelease];
group.motionEffects = #[xAxis, yAxis];
[self addMotionEffect:group];
The blurred background is the only complicated thing. If you can use an opaque color instead, use it. Otherwise it's a lot of experimenting. Also note that blurred background is not a good solution when the background is dark.
For the show/dismiss animationg, I am using the new spring animation method:
void (^animations)() = ^{
self.alpha = 1.0f;
self.transform = CGAffineTransformIdentity;
};
self.alpha = 0.0f;
self.transform = CGAffineTransformMakeScale(0.5f, 0.5f);
[UIView animateWithDuration:0.3
delay:0.0
usingSpringWithDamping:0.7f
initialSpringVelocity:0.0f
options:UIViewAnimationOptionCurveLinear
animations:animations
completion:^(BOOL completed) {
//calling UIAlertViewDelegate method
}];
I wrote a full implementation of UIAlertView that mimics the complete UIAlertView API, but adds the contentView property we've all wanted for so long: SDCAlertView.
(source: github.io)
For those who love simple and effective methods with out having to write lines of code. Here is a cool solution without using any other private frame works for adding subviews to ios 7 alert views,i.e.
[alertView setValue:imageView forKey:#"accessoryView"];
Sample code for better understanding,
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(180, 10, 85, 50)];
UIImage *wonImage = [UIImage imageNamed:#"image.png"];
[imageView setImage:wonImage];
//check if os version is 7 or above
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
[alertView setValue:imageView forKey:#"accessoryView"];
}else{
[alertView addSubview:imageView];
}
Hope it helps some one,thanks :)
For IOS7
UIAlertView *alertView1 = [[UIAlertView alloc] initWithTitle:#"Enter Form Name"
message:#""
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Ok", nil];
alertView1.alertViewStyle = UIAlertViewStyleSecureTextInput;
UITextField *myTextField = [alertView1 textFieldAtIndex:0];
[alertView1 setTag:555];
myTextField.keyboardType=UIKeyboardTypeAlphabet;
[alertView1 show];
There wont be UIAlertView with custom views in iOS7, nor contentView which Apple changed its mind about, so addSubview is impossible now in UIAlertView.
A good alternative will be SVProgressHUD, according to many threads in Apple's forum.
Edit:
There is officially no addSubview nor subclassing for UIAlertView in iOS7.
The UIAlertView class is intended to be used as-is and does not
support subclassing. The view hierarchy for this class is private and
must not be modified.
Other good alternatives:
ios-custom-alertview by wimagguc
MZFormSheetController.
You can find simple solution without extra classes here
It is based on setting accessoryView for ordinary UIAlertView.
PKAlertController (https://github.com/goodpatch/PKAlertController) is great library. I tested a lot of similar libraries and just this satisfied all my requirements.
Why it is cool:
Supports custom view
Supports iOS7
It is view controller
It behaves and looks like native alert view, including motion effects
Customizable
Similar interface like in UIAlertController

ToolTips in iOS through native UI Controls?

How do I create tooltips or something similar in iOS, without using any third party classes? I have a UIButton that I'd like to have a tooltip popup for a few seconds or until it's cleared. I have seen third party classes and libraries, but want to know if natively it's supported. I also want to show an arrow popping up from where the tooltip is coming from. I've seen some UIActionSheet Popups have this arrow.
Cheers,
Amit
Well I ended up using the third party tooltip CMTopTipView afterall. It's relatively low overhead, just a header and implementation. Modified it slightly to account for ARC. Here is what I did:
#import "CMPopTipView.h"
CMPopTipView *navBarLeftButtonPopTipView;
- (void) dismissToolTip
{
[navBarLeftButtonPopTipView dismissAnimated:YES];
}
- (void) showDoubleTap
{
navBarLeftButtonPopTipView = [[CMPopTipView alloc]
initWithMessage:#"DOUBLE Tap \n to view details"] ;
navBarLeftButtonPopTipView.delegate = self;
navBarLeftButtonPopTipView.backgroundColor = [UIColor darkGrayColor];
navBarLeftButtonPopTipView.textColor = [UIColor lightTextColor];
navBarLeftButtonPopTipView.opaque = FALSE;
[navBarLeftButtonPopTipView presentPointingAtView:catButton1
inView:self.view animated:YES];
navBarLeftButtonPopTipView.alpha = 0.75f;
NSTimer *timerShowToolTip = [NSTimer scheduledTimerWithTimeInterval:5.0
target:self
selector:#selector(dismissToolTip) userInfo:nil repeats:NO];
}
If you are on iPad you could use UIPopoverView. You also have the UIMenuController to work with for 'popover' like functionality on iPhone or iPad: tutorial. Beyond that you could just make your own UIView subclass to do this but then you'd have to handle the arrow yourrself.
Well what I ended up doing was relatively simple. I ended up using UIActionSheet with no Buttons just a text. Then used a showFromRect from a coordinate plane where the UIButton was in self.view.
UIActionSheet *popup = [[UIActionSheet alloc]
initWithTitle:#"DOUBLE Tap \n to view details."
delegate:self cancelButtonTitle:#"Cancel"
destructiveButtonTitle:nil otherButtonTitles: nil];
[popup sizeToFit];
popup.tag = 9999;
CGRect myImageRect = CGRectMake(240.0f, 605.0f, 30.0f, -40.0f);
[popup showFromRect:myImageRect inView:self.view animated:YES];
I may just suck it up and use CMPopTipView (third party control) to adjust it's size and opacity and fading alpha.
I saw that some of you is using CMPopTip, great "library".
Cool way!
Just a few things, if you use that in iOS7, you have some deprecation.
New use of the text deprecated part (this is an example)
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
paragraphStyle.alignment = self.titleAlignment;
[self.title drawInRect:titleFrame withAttributes:#{NSFontAttributeName:self.titleFont,NSParagraphStyleAttributeName:paragraphStyle}];
Bye!

dim AND lock the background when using UIActionSheet on iPad

I have researched this question for a few hours, sounds pretty simple to me but haven't been able to find a viable solution. I have an iPad application where I'm using a UIActionSheet to confirm a delete. I'm adding a label to increase the font size. Everything looks and works great. I also have a requirement to dim and lock the background while the Action Sheet is visible. I can dim but cannot see how to lock the background so that the user must make a selection on the Action Sheet to dismiss it. I have tried setting UserInteractionEnabled but it doesn't work. Any Ideas?
// dim the background
UIView *dimViewDelete = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1024, 768)];
dimViewDelete.backgroundColor = [UIColor blackColor];
dimViewDelete.alpha = 0.3f;
dimViewDelete.tag = 2222;
[self.view addSubview:dimViewDelete];
if ([self.listArray count] > 0)
{
// create Action Sheet
UIActionSheet * action = [[UIActionSheet alloc]
initWithTitle:#" "
delegate:self
cancelButtonTitle:#"Cancel"
destructiveButtonTitle:#"Delete"
otherButtonTitles:nil];
[action addButtonWithTitle:#"Cancel"];
[action setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
[action showInView:self.view];
// change the font size of the title
CGRect oldFrame = [(UILabel*)[[action subviews] objectAtIndex:0] frame];
UILabel *addTitle = [[UILabel alloc] initWithFrame:oldFrame];
addTitle.font = [UIFont boldSystemFontOfSize:22];
addTitle.textAlignment = UITextAlignmentCenter;
addTitle.backgroundColor = [UIColor clearColor];
addTitle.textColor = [UIColor whiteColor];
addTitle.text = #"Are You Sure?";
[addTitle sizeToFit];
addTitle.frame = CGRectMake(oldFrame.origin.x, oldFrame.origin.y,
oldFrame.size.width, addTitle.frame.size.height);
[action addSubview:addTitle];
}
Your best option is to implement your own custom action sheet-like control.
You need a simple view controller that has the two buttons and a label (for the title). Show the view controller in a popover. Make the view controller modal so it can only be dismissed by tapping one of the buttons. This also makes the background appear locked.
If you really need to dim the background as well, just before displaying the popover, add a screen sized UIView to the main window. Set this view's background to [UIColor whiteColor:0 alpha:0.7]. Adjust the alpha as needed to get the right dimming effect. You can even animate the alpha of the view so it fades in and out as needed.

Xcode: How To Create A PopUp View Controller That Appears In Another View Controller

Basically what I am trying to figure out to do is, say I have one View Controller, called V1, that has a regular view inside it and a button. Now, when you tap that button, I want that button to create an action that pop-ups another View Controller, called V2, within the same view controller, V1.
V2 will be reduced in size some so that it does not fill the entire screen, but you can still see the first layer which is V1 behind V2. So basically, you never really leave V1. I hope this makes sense for what I'm trying to do. I know the MTV app has this functionity. An image of what I'm talking about is here: https://docs.google.com/leaf?id=0BzlCAVXRsIPcNWUxODM2MDAtNDE3OS00ZTc4LTk5N2MtZDA3NjFlM2IzNmZk&hl=en_US
Sample code or an example is what I'm looking for as well.
Thanks
You can create such view by setting appropriate property type of modalPresentationStyle. See my example below:
UIViewController *V2 = [[UIViewController alloc] init];
V2.modalPresentationStyle = UIModalPresentationFormSheet;
V2.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[V1 presentViewController:V2 animated:YES completion:nil];
V2.view.superview.frame = CGRectMake(0, 0, 540, 620); //it's important to do this after presentModalViewController
V2.view.superview.center = V1.view.center;
[V1 release];
Try this:
V2 *d = [[V2 alloc]initWithNibName:#"V2" bundle:nil];//assuming V2 is name of your nib as well
d.delegate = self; //Optional:you only need this if you want to delegate
//create popover and put V2 in the popover view
UIPopoverController *popoverController = [[UIPopoverController alloc] initWithContentViewController:d];
popoverController.delegate = self; //optional
CGSize size = CGSizeMake(325, 75); // size of view in popover…V2
popoverController.popoverContentSize = size;
[d release];
[popoverController presentPopoverFromRect:yourButton.frame inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
If you want to present this as a modal popup in iOS 8 with a similar style to the OP's screenshot here's what I did:
UIViewController *V2 = [[UIViewController alloc] init]; // V2 is the popup
V2.modalPresentationStyle = UIModalPresentationFormSheet;
V2.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
V2.preferredContentSize = CGSizeMake(325, 75); // size of popup view
[V1 presentModalViewController:V2 animated:YES]; // V1 is the current topmost view controller
I like this better than using a UIPopover because you don't need to mess with arrow directions and the user cannot close it by tapping outside of the popup.
These properties can also be set in a storyboard/nib via the designer. To set preferredContentSize check "Use Preferred Explicit Size" and set the values.
This only works on the iPad.
There is a very good library to display a view controller as Popup on iPhone
see here https://github.com/martinjuhasz/MJPopupViewController
If you're using Storyboard, you can follow this step:
Add a view controller (V2), setup the UI the way you want it
*based on the image you attached
add an UIView - set background to black and opacity to 0.5
add an UIImageView - that will serve as your popup (Pls take note that the image and the view must not have the same level/hierarchy. Dont make the imageview the child of the view otherwise the opacity of the uiview will affect the uiImageView)
Present V2 Modally
Click the segue. In the Attributes inspector, Set Presentation as Over Full Screen. Remove animation if you like
Select V2. In the Attributes inspector, Set Presentation as Over Full Screen. Check Defines Context and Provides Context
Select the MainView of your V2 (Pls. Check image). Set backgroundColor to Clear Color
file .m ---> this is the implementation file
-(IBAction)anyAlert:(id)sender{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Title" message:#"A Message" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"OK!", #"Other Title", nil];
[alert show];
[alert release];
}
remember declare
-(IBAction)anyAlert:(id)sender;
in the file .h ---> header file
It works for me, hopefully for you...
Create UIView for v2 and add in v1.
- (void)viewDidLoad
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:#selector(aMethod:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:#"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[self.view addSubview:button];
}
- (void)aMethod:(id)sender
{
CGRect * imageFrame = CGRectMake(10, 90, 300, 300);
V2 *v2 = [[V2 alloc] initWithFrame:imageFrame];
[self.view addSubview:v2];
}

Resources