I am trying to move a UIImage, first button press creates the image and second press moves it.
The image only needs to exist upon pressing the button.
In the simulator it creates the button and places it, the second time it click just doesn't do anything.
This is my Code
- (IBAction) btn:(id)sender {
UIImageView *myImage = [[UIImageView alloc] init];
myImage.image = [UIImage imageNamed:#"keyframe"];
if (startUp == 1){
//Create Image and add to view
myImage.frame = CGRectMake(200, 300, 10, 10);
myImage.image = [UIImage imageNamed:#"keyframe"];
[self.view addSubview:myImage];
//Set startUp to 0 and output rect value
startUp = 0;
NSLog(#"currentFrame %#", NSStringFromCGRect(myImage.frame));
}else if (startUp == 0){
//Change position, size and log to debug
myImage.frame = CGRectMake(500,100 ,20, 20);
NSLog(#"newFrame %#", NSStringFromCGRect(myImage.frame));
}
}
How do you programmatically move a programmatically added UIimage?
I tried changing the center value but that doesn't work either.
Try something like this – tested and working sample:
#import "ViewController.h"
#interface ViewController () {
BOOL startUp;
UIImageView *myImage;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
startUp = YES;
}
- (IBAction)doWork:(id)sender {
if (startUp) {
UIImage *img = [UIImage imageNamed: #"keyframe"];
myImage = [[UIImageView alloc] initWithImage: img];
[myImage sizeToFit];
[myImage setCenter: CGPointMake(200, 300)];
[self.view addSubview: myImage];
startUp = NO;
} else {
[myImage setCenter: CGPointMake(400, 500)];
}
}
#end
Related
I have used third party lib to show array of images in a slider . The images in an array comes from server, now i want to show the image in a bigger image view on a tap gesture. When anyone of the image user tap it should be shown in big imageview. I have tried some code but it is not working. My code is,
int i=0;
tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(expandImage:)];
tap.numberOfTapsRequired = 1;
[_ImageView setUserInteractionEnabled:YES];
[_ImageView addGestureRecognizer:tap];
tap = [_imagesData objectAtIndex:i];
NSLog(#"TTT %#",tap);
[self.view addSubview:_fullImage];
The method is ,
-(void)expandImage:(UITapGestureRecognizer*)recogniser
{
[self.view addSubview:_fullImage];
UIButton *closeButton = [[UIButton alloc]init];
[closeButton setTitle:#"Close" forState:UIControlStateNormal];
// [closeButton addTarget:self action:#selector(Closetab) forControlEvents:UIControlEventTouchUpInside];
[_fullImage addSubview:closeButton];
UIImageView *photoView = [[UIImageView alloc]init];
[photoView setBackgroundColor:[UIColor blueColor]];
[_fullImage addSubview:photoView];
// photoView.accessibilityIdentifier = #"nature2.png";
[_fullImage addSubview:_fullImage];
}
here I attached the sample project , customize yourself
step1
create the one full screen view for preview the image (use one UIView, one close btn, one imageview)
#interface ViewController () <UIScrollViewDelegate, TAPageControlDelegate>
{
NSTimer *timer;
NSInteger index;
//
IBOutlet UIImageView *imgfull;
IBOutlet UIView *fullimagevie;
IBOutlet UIButton *btnClose;
}
step2
add the gesture for tap the image event and set the frame of your duplicate view as bottom of viewcontroller
- (void)viewDidLoad
{
[super viewDidLoad];
[self setviewframe:self.view.frame.size.height + 10];
self.imagesData = #[#"image1.jpg", #"image2.jpg", #"image3.jpg"];
for(int i=0; i<self.imagesData.count;i++){
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetWidth(self.view.frame) * i, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.scrollView.frame))];
imageView.contentMode = UIViewContentModeScaleAspectFill;
imageView.image = [UIImage imageNamed:[self.imagesData objectAtIndex:i]];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(expandImage:)];
tap.numberOfTapsRequired = 1;
tap.view.tag = i;
[imageView setUserInteractionEnabled:YES];
[imageView addGestureRecognizer:tap];
[self.scrollView addSubview:imageView];
}
step3
handle the image tap for preview the image
-(void)expandImage:(UITapGestureRecognizer*)recogniser
{
imgfull.image = [UIImage imageNamed:[self.imagesData objectAtIndex:recogniser.view.tag]];
[UIView transitionWithView:fullimagevie
duration:0.4
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
[self setviewframe:0];
}
completion:NULL];
}
step4
dismiss the bigger image view on tap the close button
- (IBAction)btnClose:(UIButton *)sender {
[UIView transitionWithView:fullimagevie
duration:0.4
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
[self setviewframe:self.view.frame.size.height + 10];
}
completion:NULL];
}
step5
create the common method for set the frame for your bigger imageview
-(void)setviewframe:(CGFloat)coordinate{
CGRect modifyframe = fullimagevie.frame;
modifyframe.origin.y = coordinate;
fullimagevie.frame = modifyframe;
}
Hi I am new to iOS how to create scroll view with images programmatically
like this I have tried, I am getting scroll view with images in horizontal but the images are placed like below pic
Am I doing in correct way?
please help me .
Thanks
#property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
#property (strong, nonatomic) IBOutlet UIImageView *imageView;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// CGRectMake(0, 0, 600, 200);
_scrollView.tag = 1;
_scrollView.autoresizingMask=UIViewAutoresizingNone;
NSLog(#"--->%#",_scrollView);
[self.view addSubview:_scrollView];
[self setupScrollView:_scrollView];
UIPageControl *pgCtr = [[UIPageControl alloc] initWithFrame:CGRectMake(0, 154, 480, 36)];
NSLog(#"--->%#",pgCtr);
[pgCtr setTag:12];
pgCtr.numberOfPages=10;
pgCtr.autoresizingMask=UIViewAutoresizingNone;
[self.view addSubview:pgCtr];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)setupScrollView:(UIScrollView*)scrMain {
// we have 10 images here.
// we will add all images into a scrollView & set the appropriate size.
for (int i=1; i<=3; i++) {
// create image
UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:#"abc%d.png",i]];
// create imageView
_imageView = [[UIImageView alloc] initWithFrame:CGRectMake(((i-1)*scrMain.frame.size.height+5), 0, 320, 195)];
// set scale to fill
_imageView.contentMode=UIViewContentModeScaleToFill;
// set image
[_imageView setImage:image];
// apply tag to access in future
_imageView.tag=i+1;
NSLog(#"--->%#",_imageView);
// add to scrollView
[scrMain addSubview:_imageView];
}
// set the content size to 10 image width
[scrMain setContentSize:CGSizeMake(320*3, scrMain.frame.size.height)];
NSLog(#"--->%#",scrMain);
// enable timer after each 2 seconds for scrolling.
[NSTimer scheduledTimerWithTimeInterval:7 target:self selector:#selector(scrollingTimer) userInfo:nil repeats:YES];
}
- (void)scrollingTimer {
// access the scroll view with the tag
UIScrollView *scrMain = (UIScrollView*) [self.view viewWithTag:1];
NSLog(#"--->%#",scrMain);
// same way, access pagecontroll access
UIPageControl *pgCtr = (UIPageControl*) [self.view viewWithTag:12];
NSLog(#"--->%#",pgCtr);
// get the current offset ( which page is being displayed )
CGFloat contentOffset = 194;
NSLog(#"------------------->%f",contentOffset);
// calculate next page to display
int nextPage = (int)(contentOffset/scrMain.frame.size.height) + 1 ;
NSLog(#"%d",nextPage);
// if page is not 10, display it
if( nextPage!=10 ) {
[scrMain scrollRectToVisible:CGRectMake(0, nextPage*scrMain.frame.size.height, scrMain.frame.size.width, scrMain.frame.size.height) animated:YES];
NSLog(#"--->%#",scrMain);
pgCtr.currentPage=nextPage;
// else start sliding form 1 :)
} else {
[scrMain scrollRectToVisible:CGRectMake(0, 0, scrMain.frame.size.width, scrMain.frame.size.height) animated:YES];
NSLog(#"-------------------------------------------->%#",scrMain);
pgCtr.currentPage=0;
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
I think, you are wrong at this line:
// create imageView
_imageView = [[UIImageView alloc] initWithFrame:CGRectMake(((i-1)*scrMain.frame.size.height+5), 0, 320, 195)];
It should be:
// create imageView // change height to width
_imageView = [[UIImageView alloc] initWithFrame:CGRectMake(((i-1)*scrMain.frame.size.width+5), 0, 320, 195)];
Please implement this code.Hope this works and use these macros.
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
- (void)setupScrollView:(UIScrollView*)scrMain
{
for (int i=0; i<3; i++)
{
UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:#"abc%d.png",i]];
UIImageView *_imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i*SCREEN_WIDTH, 0, SCREEN_WIDTH, 195)];
_imageView.contentMode=UIViewContentModeScaleToFill;
[_imageView setImage:image];
_imageView.tag=i;
[scrMain addSubview:_imageView];
}
[scrMain setContentSize:CGSizeMake(SCREEN_WIDTH*3, scrMain.frame.size.height)];
[NSTimer scheduledTimerWithTimeInterval:7 target:self selector:#selector(scrollingTimer) userInfo:nil repeats:YES];
}
You can add custom view to Scrollview and in Custom view add UIImageview as subview with some padding left and right?
I am trying to check if a image of a subview is hidden or not, by clicking a button. The log does display but i cant get the hidden status of the image somehow.
Whats going wrong here? Hope u can help me!
Viewdidload:
SubSlide1Hoofdstuk3 *subslide1 = [[SubSlide1Hoofdstuk3 alloc] init];
CGRect frame = self.view.frame;
frame.origin.x = 0;
frame.origin.y = 0;
subslide1.view.frame = frame;
// This works finaly
UIImageView *zwart = subslide1.imageZwart;
[zwart setImage:[UIImage imageNamed:#"imageblack.jpg"]];
[subslide1.b1 addTarget:self action:#selector(switchImageZwart:) forControlEvents:UIControlEventTouchUpInside];
[_scrollView addSubview:subslide1.view];
The IBAction to check the image in subview is hidden:
-(IBAction)switchImageZwart:(id)sender
{
SubSlide1Hoofdstuk3 *switchactie = [[SubSlide1Hoofdstuk3 alloc] init];
UIImageView *wit = switchactie.imageWit;
UIImageView *zwart = switchactie.imageZwart;
if(zwart.hidden == YES) {
NSLog(#"Image black is hidden!");
} else if(wit.hidden == YES) {
NSLog(#"Image white is hidden!");
} else {
NSLog(#"Can't say... :(");
}
}
The problem here is that inside your -(IBAction)switchImageZwart:(id)sender method you create a new instance of SubSlide1Hoofdstuk3 and checking its properties (the UIImageViews) instead of checking the actual UIImageView objects you created on viewDidLoad:. What you want actually is to hold a reference to subslide1 and check that instead.
Ps. Since the button calling the check method is actually a subview of your subslide1, you could get a reference like:
SubSlide1Hoofdstuk3 *switchactie = [sender superView];
EDIT: An example on your actual code:
in your .h file:
#property(nonatomic, strong) SubSlide1Hoofdstuk3 *subslide1;
in your .m file:
#synthesize subslide1;
- (void)viewDidLoad
{
//...
self.subslide1 = [[SubSlide1Hoofdstuk3 alloc] init];
CGRect frame = self.view.frame;
frame.origin.x = 0;
frame.origin.y = 0;
self.subslide1.view.frame = frame;
// This works finaly
UIImageView *zwart = self.subslide1.imageZwart;
[zwart setImage:[UIImage imageNamed:#"imageblack.jpg"]];
[self.subslide1.b1 addTarget:self action:#selector(switchImageZwart:) forControlEvents:UIControlEventTouchUpInside];
[_scrollView addSubview:self.subslide1.view];
}
-(IBAction)switchImageZwart:(id)sender
{
SubSlide1Hoofdstuk3 *switchactie = self.subslide1;
UIImageView *wit = switchactie.imageWit;
UIImageView *zwart = switchactie.imageZwart;
if(zwart.hidden == YES) {
NSLog(#"Image black is hidden!");
} else if(wit.hidden == YES) {
NSLog(#"Image white is hidden!");
} else {
NSLog(#"Can't say... :(");
}
}
I have a lot of trouble to accomplish this task on an ipad : when double tape on an image switch this image to full screen and when double taping again come back to the original display, same thing using pinching. I'm using UIGestureRecognizer to try to do this. Thanks for your help.
GesturesViewController.h
#import <UIKit/UIKit.h>
#interface GesturesViewController : UIViewController
<UIActionSheetDelegate>{
IBOutlet UIImageView *imageView;
}
#property (nonatomic, retain) UIImageView *imageView;
#end
GesturesViewController.m
#import "GesturesViewController.h"
#import "GesturesAppDelegate.h"
#implementation GesturesViewController
#synthesize imageView;
CGRect originalFrame,fullScreenFrame;
BOOL isFullScreenMode;
- (void)viewDidLoad {
// Loading test image
imageView.image = [UIImage imageNamed:#"image1.jpg"];
//---tap gesture---
isFullScreenMode = NO;
originalFrame = CGRectMake(imageView.frame.origin.x,imageView.frame.origin.y,imageView.frame.size.width,imageView.frame.size.height);
//changes
fullScreenFrame = CGRectMake(0,0,768,1004);
UITapGestureRecognizer *tapGesture =
[[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleTapGesture:)];
tapGesture.numberOfTapsRequired = 2;
[imageView addGestureRecognizer:tapGesture];
[tapGesture release];
//---pinch gesture---
UIPinchGestureRecognizer *pinchGesture =
[[UIPinchGestureRecognizer alloc] initWithTarget:self action:#selector(handlePinchGesture:)];
[imageView addGestureRecognizer:pinchGesture];
[pinchGesture release];
[super viewDidLoad];
}
//---handle tap gesture---
-(IBAction) handleTapGesture:(UIGestureRecognizer *) sender {
// HOW TO ACCOMPLISH THIS PART
if (isFullScreenMode)
[imageView setFrame:originalFrame];
else
[imageView setFrame:fullScreenFrame];
[imageView setCenter:CGPointMake(self.view.frame.size.width/2,self.view.frame.size.height/2)];
isFullScreenMode = !isFullScreenMode;
NSLog(#"Image View : %#",imageView);
}
//---handle pinch gesture---
-(IBAction) handlePinchGesture:(UIGestureRecognizer *) sender {
CGFloat factor = [(UIPinchGestureRecognizer *) sender scale];
if (sender.state == UIGestureRecognizerStateEnded){
// HOW TO ACCOMPLISH THIS ---
if (factor > 1 && !isFullScreenMode) {
//---pinching in---
[imageView setFrame:fullScreenFrame];
} else {
//---pinching out---
[imageView setFrame:originalFrame];
}
isFullScreenMode = !isFullScreenMode;
[imageView setCenter:CGPointMake(self.view.frame.size.width/2,self.view.frame.size.height/2)];
}
NSLog(#"Image View : %#",imageView);
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[images release];
[imageView release];
[super dealloc];
}
#end
Thanks.
- (void)toggleZoom:(UITapGestureRecognizer *)gestureRecognizer
{
if (proxyView)
{
CGRect frame =
[proxyView.superview
convertRect:self.view.frame
fromView:self.view.window];
self.view.frame = frame;
CGRect proxyViewFrame = proxyView.frame;
[proxyView.superview addSubview:self.view];
[proxyView removeFromSuperview];
[proxyView autorelease];
proxyView = nil;
self.view.frame = proxyViewFrame;
}
else
{
proxyView = [[UIView alloc] initWithFrame:self.view.frame];
proxyView.hidden = YES;
proxyView.autoresizingMask = self.view.autoresizingMask;
[self.view.superview addSubview:proxyView];
CGRect frame =
[self.view.window
convertRect:self.view.frame
fromView:proxyView.superview];
[self.view.window addSubview:self.view];
self.view.frame = frame;
self.view.frame = self.view.window.bounds;
}
}
I have selected only necessary portion of the code...... its from ZoomingViewController....
If you see its same as we have discussed earlier..... but with few improvements.......
For doing this you have to first store your original frame size somewhere globally so that you can reassing it later on.
you need create two global frames
CGRect originalFrame, fullScreenFrame;
//in viewDidLoad initialize these frames... originalFrame with imageView frame and
fullScreenFrame with the iPad window coordinates........ but remeber this can distort the
aspect ratio so just calculate the aspect ratio of original image by using its height and
width and accordingly create the full screen frame for the image.......
and just assign these frames in your gesture action.
Thanks,
in
viewDidLoad
originalFrame = imageView.frame;
or
originalFrame = CGRectMake(imageView.frame.origin.x,imageView.frame.origin.y,imageView.frame.size.width,imageView.frame.size.height);
appDelegate <----- get the instance of your appdelegate object so that we can retrieve the window object.......
UIWindow *tempWindow = [appDelegate window];
fullScreenFrame = CGRectMake(tempWindow .frame.origin.x,tempWindow .frame.origin.y,tempWindow .frame.size.width,tempWindow.frame.size.height);
//**in event just set frame of the imageView-- for knowing the current state-- whether its fullScreen or original frame we need to have a flag........it should be global...
so declare a global flag ....BOOL isFullScreenMode and initialize it as NO in
viewDidLoad
isFullScreenMode = NO;
in gesture actions just check this flag and write following...
if (isFullScreenMode)
[imageView setFrame:originalFrame];
else
[imageView setFrame:fullScreenFrame];
isFullScreenMode = !isFullScreenMode;
#implementation ImageFullScreen
#synthesize myImage;
#import "GesturesViewController.h"
#import "GesturesAppDelegate.h"
#implementation GesturesViewController
#synthesize imageView;
CGRect originalFrame,fullScreenFrame;
BOOL isFullScreenMode;
- (void)viewDidLoad {
// Loading test image
imageView.image = [UIImage imageNamed:#"image1.jpg"];
//---tap gesture---
isFullScreenMode = NO;
originalFrame = CGRectMake(imageView.frame.origin.x,imageView.frame.origin.y,imageView.frame.size.width,imageView.frame.size.height);
//changes
fullScreenFrame = CGRectMake(0,0,768,1004);
UITapGestureRecognizer *tapGesture =
[[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleTapGesture:)];
tapGesture.numberOfTapsRequired = 2;
[imageView addGestureRecognizer:tapGesture];
[tapGesture release];
//---pinch gesture---
UIPinchGestureRecognizer *pinchGesture =
[[UIPinchGestureRecognizer alloc] initWithTarget:self action:#selector(handlePinchGesture:)];
[imageView addGestureRecognizer:pinchGesture];
[pinchGesture release];
[super viewDidLoad];
}
//---handle tap gesture---
-(IBAction) handleTapGesture:(UIGestureRecognizer *) sender {
// HOW TO ACCOMPLISH THIS PART
if (isFullScreenMode)
[imageView setFrame:originalFrame];
else
[imageView setFrame:fullScreenFrame];
[imageView setCenter:CGPointMake(self.view.frame.size.width/2,self.view.frame.size.height/2)];
isFullScreenMode = !isFullScreenMode;
NSLog(#"Image View : %#",imageView);
}
//---handle pinch gesture---
-(IBAction) handlePinchGesture:(UIGestureRecognizer *) sender {
CGFloat factor = [(UIPinchGestureRecognizer *) sender scale];
if (sender.state == UIGestureRecognizerStateEnded){
// HOW TO ACCOMPLISH THIS ---
if (factor > 1 && !isFullScreenMode) {
//---pinching in---
[imageView setFrame:fullScreenFrame];
} else {
//---pinching out---
[imageView setFrame:originalFrame];
}
isFullScreenMode = !isFullScreenMode;
[imageView setCenter:CGPointMake(self.view.frame.size.width/2,self.view.frame.size.height/2)];
}
NSLog(#"Image View : %#",imageView);
}
Is it possible to set some image as title of Navigation bar?
I think NYTimes application used a Navigation bar and title is look like image file (the reason why it's seems UINavigationBar is because they use right button to search).
You can use an UIImageView for the UINavigationItem.titleView property, something like:
self.navigationItem.titleView = myImageView;
I find that a transparent .png at about 35px in height has worked well.
- (void)awakeFromNib {
//put logo image in the navigationBar
UIImageView* img = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"logo.png"]];
self.navigationItem.titleView = img;
[img release];
}
You can do it right from storyboard (as of Xcode 7):
Create a view outside main view of view controller. It can be a nested view or just an image
Add navigation item to your view controller
Ctrl+ drag from navigation item and drop on outside view
4.select title view
I have created a custom category for UINavigationBar as follows
UINavigationBar+CustomImage.h
#import <UIKit/UIKit.h>
#interface UINavigationBar (CustomImage)
- (void) setBackgroundImage:(UIImage*)image;
- (void) clearBackgroundImage;
- (void) removeIfImage:(id)sender;
#end
UINavigationBar+CustomImage.m
#import "UINavigationBar+CustomImage.h"
#implementation UINavigationBar (CustomImage)
- (void) setBackgroundImage:(UIImage*)image {
if (image == NULL) return;
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(110,5,100,30);
[self addSubview:imageView];
[imageView release];
}
- (void) clearBackgroundImage {
NSArray *subviews = [self subviews];
for (int i=0; i<[subviews count]; i++) {
if ([[subviews objectAtIndex:i] isMemberOfClass:[UIImageView class]]) {
[[subviews objectAtIndex:i] removeFromSuperview];
}
}
}
#end
I invoke it from my UINavigationController
[[navController navigationBar] performSelectorInBackground:#selector(setBackgroundImage:) withObject:image];
This line will work for you, I always use this
[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:#"imageNavBar.png"] forBarMetrics:UIBarMetricsDefault];
I modified the UINavigationBar+CustomImage.m to have the title still visible to the user. Just use insertSubview: atIndex: instead of addSubview:
UINavigationBar+CustomImage.m
#import "UINavigationBar+CustomImage.h"
#implementation UINavigationBar (CustomImage)
- (void) setBackgroundImage:(UIImage*)image {
if (image == NULL) return;
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(0, 0, 320, 44);
[self insertSubview:imageView atIndex:0];
[imageView release];
}
- (void) clearBackgroundImage {
NSArray *subviews = [self subviews];
for (int i=0; i<[subviews count]; i++) {
if ([[subviews objectAtIndex:i] isMemberOfClass:[UIImageView class]]) {
[[subviews objectAtIndex:i] removeFromSuperview];
}
}
}
#end
This also works well too
[self.navigationController.navigationBar.topItem setTitleView:[[UIImageView alloc]initWithImage:[UIImage imageNamed:#"YourLogo"]]];
Do it quickly using storyboard and #IBDesignable:
#IBDesignable class AttributedNavigationBar: UINavigationBar {
#IBInspectable var imageTitle: UIImage? = nil {
didSet {
guard let imageTitle = imageTitle else {
topItem?.titleView = nil
return
}
let imageView = UIImageView(image: imageTitle)
imageView.frame = CGRect(x: 0, y: 0, width: 40, height: 30)
imageView.contentMode = .scaleAspectFit
topItem?.titleView = imageView
}
}
}
Then in attributes inspector just select an image:
and wait a second for result:
So setting view is there where it should be... in storyboard.
For those who have the same error but in Xamarin Forms, the solution is to create a Renderer in iOS app and set the image like so :
[assembly: Xamarin.Forms.ExportRenderer(typeof(Xamarin.Forms.Page), typeof(MyApp.Renderers.NavigationPageRenderer))]
namespace MyApp.Renderers
{
#region using
using UIKit;
using Xamarin.Forms.Platform.iOS;
#endregion
public class NavigationPageRenderer : PageRenderer
{
public override void ViewDidLoad()
{
base.ViewDidLoad();
SetTitleImage();
}
private void SetTitleImage()
{
UIImage logoImage = UIImage.FromFile(ResourceFiles.ImageResources.LogoImageName);
UIImageView logoImageView = new UIImageView(logoImage);
if (this.NavigationController != null)
{
this.NavigationController.NavigationBar.TopItem.TitleView = logoImageView;
}
}
}
}
Hope it helps someone!
I modified the UINavigationBar+CustomImage code to properly work without leaking memory.
- (void)setBackgroundImage:(UIImage *)image
{
if (! image) return;
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
[self addSubview:imageView];
[imageView release];
}
- (void) clearBackgroundImage
{
// This runs on a separate thread, so give it it's own pool
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSArray *mySubviews = self.subviews;
// Move in reverse direction as not to upset the order of elements in the array
for (int i = [mySubviews count] - 1; i >= 0; i--)
{
if ([[mySubviews objectAtIndex:i] isMemberOfClass:[UIImageView class]])
{
[[mySubviews objectAtIndex:i] removeFromSuperview];
}
}
[pool release];
}
The following is how you would do this in (Xamarin's) MonoTouch with C#.NET
Create a UIViewConvrtoller that is in a NavigationController then call this at any time:
someNiceViewControllerYouMade.NavigationController.NavigationBar
.InsertSubview(new UIImageView
(MediaProvider.GetImage(ImageGeneral.navBar_667x44)),0);
Note: MediaProvider is just a class that fetches images.
This example allows for the view to fill the full Navigation Bar , and lets the text for the items caption appear too.
If your buttons disappear when you navigate back and forth the navigation, this fixed it for me:
NSArray *mySubviews = navigationBar.subviews;
UIImageView *iv = nil;
// Move in reverse direction as not to upset the order of elements in the array
for (int i = [mySubviews count] - 1; i >= 0; i--)
{
if ([[mySubviews objectAtIndex:i] isMemberOfClass:[UIImageView class]])
{
NSLog(#"found background at index %d",i);
iv = [mySubviews objectAtIndex:i];
[[mySubviews objectAtIndex:i] removeFromSuperview];
[navigationBar insertSubview:iv atIndex:0];
}
}
Just use
[navController.navigationBar insertSubview:myImage atIndex:0] ;
where myImage is of type UIImageView
and navController is of type UINavigationController
ios5.0 introduced a heap of features to customise the appearance of standard elements. If you didn't want to use an ImageView for the title, an alternative would be to customise the appearance of all UINavbars using a background image and a custom font/colour.
- (void) customiseMyNav
{
// Create resizable images
UIImage *portraitImage = [[UIImage imageNamed:#"nav_bar_bg_portrait"]
resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
UIImage *landscapeImage = [[UIImage imageNamed:#"nav_bar_bg_landscape"]
resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
// Set the background image
[[UINavigationBar appearance] setBackgroundImage:portraitImage forBarMetrics:UIBarMetricsDefault];
[[UINavigationBar appearance] setBackgroundImage:landscapeImage forBarMetrics:UIBarMetricsLandscapePhone];
// set the title appearance
[[UINavigationBar appearance] setTitleTextAttributes:
[NSDictionary dictionaryWithObjectsAndKeys:
[UIColor colorWithRed:50.0/255.0 green:150.0/255.0 blue:100/255.0 alpha:1.0],
UITextAttributeTextColor,
[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.6],
UITextAttributeTextShadowColor,
[NSValue valueWithUIOffset:UIOffsetMake(0, -1)],
UITextAttributeTextShadowOffset,
[UIFont fontWithName:#"Arial-Bold" size:0.0],
UITextAttributeFont,
nil]];
}
In MonoTouch you can use this:
this.NavigationItem.TitleView = myImageView;
Add image to naviagtionBar with SWIFT that scales to fit and clips to bounds. You can call this function inside the view controllers viewDidLoad() function.
func setupNavigationBarWithTitleImage(titleImage: UIImage) {
let imageView = UIImageView(image: titleImage)
imageView.contentMode = .ScaleAspectFit
imageView.clipsToBounds = true
navigationItem.titleView = imageView
}