how do i add a UIView controller to a UIView - ios

i have a custom class of type UIViewController. i want to add it to a UIView so that it can be used to output to the screen.
the UIView is called engineView
my custom UIViewController is called Engine. there is a custom method in the controller called addImage.
the code is as follows:
Engine *engine = [[Engine alloc] init];
CGRect frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
engine.view.frame = frame;
UIImage *image = [UIImage imageNamed:#"photo2.jpg"];
[engine addImage:image];
[engineView addSubview: engine.view];
this does not display the image.
however if i add the view controller through storyboard, it seems to work (if i add the image at the viewdidlayoutsubviews method. but i would like to call functions to it programically from the parent UIViewCcontroller.
can anyone tell me how i do this?

You can set storyBoard identifier in interface builder and ca use it like suggested above.
MyViewController *instance = [self.storyBoard instantiateViewControllerWithIdentifier:#"yourIdentifier"];
As far as adding a ViewController to UIView you can achieve that by using addChildViewControllermethod too.

try this..
Engine *eng=[self.storyboardinstantiateViewControllerWithIdentifier:#"YourStoryboradId"];
*you can set storyboard id by going in Identity Inspector.
After that You can add image on your View Controller by following code
UIImageView *image=[UIImageView alloc]initWithFrame:CGRectMake(x, y, your width, your Height);
img setImage:[UIImage imageNamed:#"imageName"];
[eng addSubview:image];

try like this..
Engine *engine = (Engine *)[self.storyboard instantiateViewControllerWithIdentifier:#"EngineViewControllerStoryBoardID"];
to set the story board id
to pass an image to Engine:
-->create a UIImage property in Engine.h
like #Property UIImage * engineImage;
--> assign that image to UIIMageView in Engine.m
-(void)viewWillAppear:(BOOL)animated
{
engineImageView.image = engineImage; // engineImageView is an example UIImageView replace it with your UIImageView
}
--> now send the image like
engine.engineImage =[UIImage imageNamed:#"photo2.jpg"];

Related

Custom UINavigationBar with custom height in center

I have reviewed almost all questions on OS related to custom NavigationBar but unable to find those solutions helpful. Please have a look on following screenshot,
Red portion represents an icon (small image) in the center of navigationBar.
Please suggest some solution. Thanks in advance.
EDIT: I want to implement that for all UINavigationBar in app. I mean on each view
NOTE: I do not know who is down voting my question but i want to ask a question from those persons. Do you have any solution for my problem? If not, then why you are down voting my question? I will not be able to get help in this way. It's totally wrong.
You can subclass UINavigationBar.
#import "VSNavigationBar.h"
#interface VSNavigationBar ()
#property (nonatomic, weak) UIView *noseView;
#end
#implementation VSNavigationBar
-(void)layoutSubviews
{
[super layoutSubviews];
static CGFloat width = 80;
if (!_noseView) {
UIView *noseView = [[UIView alloc] initWithFrame:CGRectMake(self.bounds.size.width / 2 - width / 2, 0, width, width)];
self.noseView = noseView;
self.noseView.backgroundColor = self.barTintColor;
self.noseView.layer.cornerRadius = self.noseView.frame.size.width / 2;
[self addSubview:_noseView];
}
_noseView.frame = CGRectMake(self.bounds.size.width / 2 - width / 2, 0, width, width);
}
#end
And in your Storyboard you would select the NavigationController scene, in the tree view on the left select Navigation Bar and on the right side select the identity inspector and change the class to the subclass.
you need to create an image that looks like central part of the image you have provided and say -
UIImage *image = [UIImage imageNamed: #"logo.png"];
UIImageView *imageview = [[UIImageView alloc] initWithImage: image];
self.navigationItem.titleView = image view;
If you are trying to get circular effect like the bottom of the image you provided, in that case you need to have same image as above and set it as background image of navbar -
[navigationBar setBackgroundImage:[UIImage imageNamed: #"yourImage"] forBarMetrics:UIBarMetricsDefault];

PresentViewController after UIImage filter not working

I have to apply blur effect like iOS 7 when i am presenting a modal view controller so that the background is clear and can see the blur effect. Following is the code i am using, but i need to present this view controller after a timer is finished. But its just showing a blur image in the background and not presenting the view controller.
UIImageView *imgView = [[UIImageView alloc]init];
imgView.frame = [[UIScreen mainScreen]bounds];
[[[GCAppDelegate instance]window] addSubview:imgView];
UIImage *image= [self getScreenShotOfWindow];
messageViewController = (GCMessageSelectionViewController *)[self.storyboard instantiateViewControllerWithIdentifier:#"GCMessageSelectionViewController"];
[self presentViewController:messageViewController animated:YES completion:^(){
//put your code here
imgView.image = image;
}];
messageViewController is probably pushed but is covered by the blur image.
try assigning imgView to messageViewController's view.

iOS 7 Translucent Modal View Controller

The App Store app on iOS 7 uses a frosted glass-type effect where it is possible to see the view behind. Is this using an API built into iOS 7 or is it custom code. I was hoping it would be the former but I can't see any obvious references in the documentation. Obvious things like (like setting the alpha property on the modal view) don't seem to have any effect.
To see an example, open the App Store app and press the button at the top-right.
With the release of iOS 8.0, there is no need for getting an image and blurring it anymore. As Andrew Plummer pointed out, you can use UIVisualEffectView with UIBlurEffect.
UIViewController * contributeViewController = [[UIViewController alloc] init];
UIBlurEffect * blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
UIVisualEffectView *beView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
beView.frame = self.view.bounds;
contributeViewController.view.frame = self.view.bounds;
contributeViewController.view.backgroundColor = [UIColor clearColor];
[contributeViewController.view insertSubview:beView atIndex:0];
contributeViewController.modalPresentationStyle = UIModalPresentationOverCurrentContext;
[self presentViewController:contributeViewController animated:YES completion:nil];
Solution that works before iOS 8
I would like to extend on rckoenes' answer:
As emphasised, you can create this effect by:
Convert the underlying UIView to an UIImage
Blur the UIImage
Set the UIImage as background of your view.
Sounds like a lot of work, but is actually done pretty straight-forward:
1. Create a category of UIView and add the following method:
-(UIImage *)convertViewToImage
{
UIGraphicsBeginImageContext(self.bounds.size);
[self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
2. Make an image of the current view and blur it by using Apple's Image Effect category (download)
UIImage* imageOfUnderlyingView = [self.view convertViewToImage];
imageOfUnderlyingView = [imageOfUnderlyingView applyBlurWithRadius:20
tintColor:[UIColor colorWithWhite:1.0 alpha:0.2]
saturationDeltaFactor:1.3
maskImage:nil];
3. Set it as background of your overlay.
-(void)viewDidLoad
{
self.view.backgroundColor = [UIColor clearColor];
UIImageView* backView = [[UIImageView alloc] initWithFrame:self.view.frame];
backView.image = imageOfUnderlyingView;
backView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
[self.view addSubview:backView];
}
Just reimplemented Sebastian Hojas' solution in Swift:
1. Create a UIView extension and add the following method:
extension UIView {
func convertViewToImage() -> UIImage{
UIGraphicsBeginImageContext(self.bounds.size);
self.drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
return image;
}
}
2. Make an image of the current view and blur it by using Apple's Image Effect (I found a reimplementation of this in Swift here: SwiftUIImageEffects
var imageOfUnderlyingView = self.view.convertViewToImage()
imageOfUnderlyingView = imageOfUnderlyingView.applyBlurWithRadius(2, tintColor: UIColor(white: 0.0, alpha: 0.5), saturationDeltaFactor: 1.0, maskImage: nil)!
3. Set it as background of your overlay.
let backView = UIImageView(frame: self.view.frame)
backView.image = imageOfUnderlyingView
backView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.5)
view.addSubview(backView)
I think this is the easiest solution for a modal view controller that overlays everything with a nice blur (iOS8)
UIViewController * contributeViewController = [[UIViewController alloc] init];
UIBlurEffect * blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
UIVisualEffectView *beView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
beView.frame = self.view.bounds;
contributeViewController.view.frame = self.view.bounds;
contributeViewController.view.backgroundColor = [UIColor clearColor];
[contributeViewController.view insertSubview:beView atIndex:0];
contributeViewController.modalPresentationStyle = UIModalPresentationOverCurrentContext;
[self presentViewController:contributeViewController animated:YES completion:nil];
There is no API available in the iOS 7 SDK which will allow you to "frost" the underlaying view controller.
What I have done is render the underlaying view to an image, which I then frosted and set that as background the the view that is being presented.
Apple provides a good example for this: https://developer.apple.com/downloads/index.action?name=WWDC%202013
The project you want is called, iOS_RunningWithASnap
A little simplier way to achieve this (based on Andrew Plummer's answer) with Interface Builder (also it removes side effect that appears in Andrews answer):
In IB add Visual Effect View to your View Controller under your other views;
Make top, bottom, left, right constraints from Visual Effect View to top (parent) View, set all of them to 0;
Set Blur Style;
Add the code where you present your new fancy View Controller:
UIViewController *fancyViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"yourStoryboardIDFOrViewController"];
fancyViewController.view.backgroundColor = [UIColor clearColor];
fancyViewController.modalPresentationStyle = UIModalPresentationOverCurrentContext;
[self presentViewController:fancyViewController
animated:YES
completion:nil];
Actually, the second and third lines are VERY important - otherwise controller will blink and then turn black.
Since iOS 8, this works:
let vc = UIViewController()
vc.view = UIVisualEffectView(effect: UIBlurEffect(style: .Light))
vc.modalPresentationStyle = .OverFullScreen
let nc = UINavigationController(rootViewController: vc)
nc.modalPresentationStyle = .OverFullScreen
presentViewController(nc, animated: true, completion: nil)
The key is the .OverFullScreen flag and ensuring the viewControllers have a blur UIVisualEffectView that is the first visible view.
As #rckoenes said, there is no Apple provided framework to get that effect. But some people out there already built good alternatives, like this one for example:
https://github.com/JagCesar/iOS-blur/
A couple of alternative approaches that also work on iOS 5 and 6:
FXBlurView: https://github.com/nicklockwood/FXBlurView
iOS RealtimeBlur: https://github.com/alexdrone/ios-realtimeblur
Fast & easy solution
with XIB support you can use for the old school boys
https://github.com/cezarywojcik/CWPopup
Instead of presenting the viewController as a modalView, you could add it as a child viewController and create a custom animation. You would then only need to change the default view of the viewController to a UIToolBar in viewDidLoad.
This will allow you to mimic the appstore's blurred modal view as closely as possible.
I have uploaded my take of the blurred view controller to [GitHub][1]. It also comes with a segue subclass so you can use it in your storyboards.
Repository: https://github.com/datinc/DATBlurSegue
Apple released the UIImageEffect category for those effects. Those category should be added manually to the project, and it support iOS7.
You can use UIToolbar as background.
By default UIToolbar have 50px height.
Add auto layout constraints on UIToolbar.
Then select height constraint and modify it.
Hierarchy will look like this:
UIView -> clear colour for background.
- UIToolbar
- Other contents.

Shadow in separate view from UIImage for dynamic adjustments

I would like to obtain this effect (http://stackoverflow.com/questions/7023271/how-to-adjust-drop-shadow-dynamically-during-an-uiimageview-rotation) but from a more complex image than just a red square ! If the link ever gets broken, it's a about how to adjust drop shadow dynamically during an UIImageView rotation.
So I tried implementing something but I just can't get the shadow in a separate layer... Here is my code, very simple, but doesn't work:
// here is my code
- (void)viewDidLoad {
[super viewDidLoad];
testView = [[UIImageView alloc] initWithImage: [UIImage imageNamed:#"handNoShadow.png"]];
testViewShadow = [[UIView alloc] initWithFrame:testView.frame];
testViewShadow.layer.shadowPath = [[testView layer] shadowPath];
testViewShadow.layer.shadowOpacity = 1.0;
testViewShadow.layer.shadowOffset = CGSizeMake(10, 10);
testViewShadow.layer.shadowRadius = 5.0;
[self.view addSubview:testViewShadow];
[self.view addSubview:testView];
}
PS: i did #import
I do get an image but no shadow... =(
Any lead, help, code, link... is welcome !
Thanks
possible cause:
your testViewShadow.clipToBounds property is set to YES (should be NO)
your testViewShadow do the drawing of the shadow correctly but another UIView is on top and mask it. Check your Z order. Either the order in Storyboard/Nib file (or the order you added the subviews programmatically). Last in the list (or last one added) is on top. For my app I had to put the UIView that need a shadow last so that no other view mask it.

How can I change the image displayed in a UIImageView programmatically?

I have an IBOutlet to a UIImageView, but when I look at the UIImageView doc, I can't see any hints about programmatically changing it. Do I have to fetch an UIImage object from that UIImageView?
If you have an IBOutlet to a UIImageView already, then all you have to do is grab an image and call setImage on the receiver (UIImageView). Two examples of grabbing an image are below. One from the Web, and one you add to your Resources folder in Xcode.
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://farm4.static.flickr.com/3092/2915896504_a88b69c9de.jpg"]]];
or
UIImage *image = [UIImage imageNamed: #"cell.png"];
Once you have an Image you can then set UIImageView:
[imageView setImage:image];
The line above assumes imageView is your IBOutlet.
That's it! If you want to get fancy you can add the image to an UIView and then add transitions.
P.S. Memory management not included.
Note that the NIB file doesn't wire up all the IBOutlets until the view has been added to the scene. If you're wiring things up manually (which you might be doing if things are in separate NIBs) this is important to keep in mind.
So if my test view controller has an "imageView" wired by a nib, this probably won't work:
testCardViewController.imageView.image = [UIImage imageNamed:#"EmptyCard.png"];
[self.view addSubview:testCardViewController.view];
But this will:
[self.view addSubview:testCardViewController.view];
testCardViewController.imageView.image = [UIImage imageNamed:#"EmptyCard.png"];
This worked for me
[ImageViewName setImage:[UIImage imageNamed: #"ImageName.png"]];
Make sure that the ImageView is declared properly in the .h file and is linked with the IB element.
imageView.image = [UIImage imageNamed:#"myImage.png"];
For the purpose of people who may be googling this to try to solve their problem, remember to properly declare the property in your header file and to synthesize the UIImageView in your implementation file... It'll be tough to set the image programmatically without getter and setter methods.
#import <UIKit/UIKit.h>
#interface YOURCONTROLLERNAME : UIViewController {
IBOutlet UIImageView *imageToDisplay;
}
#property (nonatomic, retain) IBOutlet UIImageView *imageToDisplay;
#end
and then in your .m :
#implementation YOURCONTROLLERNAME
#synthesize imageToDisplay;
//etc, rest of code goes here
From there you should be fine using something like the following to set your image.
[YOURCONTROLLER.imageToDisplay setImage:[UIImage imageNamed:value]];
Example in Swift:
import UIKit
class ViewController: UIViewController {
#IBOutlet var myUIImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func myAction(sender: UIButton) {
let newImg: UIImage? = UIImage(named: "profile-picture-name")
self.myUIImageView.image = newImg
}
#IBAction func myAction2(sender: UIButton) {
self.myUIImageView.image = nil
self.myUIImageView.image = UIImage(data: NSData(contentsOfURL: NSURL(string: "http://url/image.png")!)!)
}
}
Following Jordan's advice (which should work actually), try to set the UIImageView to be visible:
[imageView setHidden: NO];
and also - don't forget to attach it to the main UIView:
[mainView addSubview: imageView];
and to bring to the front:
[mainView bringSubviewToFront: imageView];
Hope combining all these steps will help you solve the mystery.
My problem was that I tried to change the image in an other thread. I did like this:
- (void)changeImage {
backgroundImage.image = [UIImage imageNamed:#"img.png"];
}
Call with:
[self performSelectorOnMainThread : #selector(changeImage) withObject:nil waitUntilDone:NO];
Don't forget to call sizeToFit() after you change image if you then use size of UIImageView to set UIScrollView contentSize and/or compute zoom scale
let image = UIImage(named: "testImage")
imageView.image = image
imageView.sizeToFit()
scrollView.contentSize = imageView.bounds.size
If you want to set image to UIImageView programmatically then Dont Forget to add UIImageView as SubView to the main View.
And also dont forgot to set ImageView Frame.
here is the code
UIImageView *myImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
myImage.image = [UIImage imageNamed:#"myImage.png"];
[self.view addSubview:myImage];
myUIImageview.image = UIImage (named:"myImage.png")
Working with Swift 5 (XCode 10.3) it's just
yourImageView.image = UIImage(named: "nameOfTheImage")
UIColor * background = [[UIColor alloc] initWithPatternImage:
[UIImage imageNamed:#"anImage.png"]];
self.view.backgroundColor = background;
[background release];
This question already had a lot of answers. Unfortunately none worked for me.
So for the sake of completenes I add what helped me:
I had multiple images with the same name - so I ordered them in sub folders. And I had the full path to the image file I wanted to show. With a full path imageNamed: (as used in all solutions above) did not work and was the wrong method.
Instead I now use imageWithContentsOfFile: like so:
self.myUIImage.image = [UIImage imageWithContentsOfFile:_currentWord.imageFileName];
Don't know, if anyone reads that far?
If so and this one helped you: please vote up.
;-)
To set image on your imageView use below line of code,
self.imgObj.image=[UIImage imageNamed:#"yourImage.png"];

Resources