Edward
Edward

Reputation: 107

Insert UIImageView as navigation bar button

I'm new with Xcode and objective-c and i tried to make an app which navigation menu could display profile picture of the owner that saved in MySQL database. I used navigation bar button but it seems cannot use UIViewImage as button. This is my code:

//Resize image
   UIImage *miniProfile=[UIImage imageNamed:@"profile_icon.png"];//this is the hardcoded version
   UIImage *tempImage = nil;
   CGSize targetSize = CGSizeMake(25,25);
   UIGraphicsBeginImageContext(targetSize);
   CGRect thumbnailRect = CGRectMake(0, 0, 0, 0);
   thumbnailRect.origin = CGPointMake(0.0,0.0);
   thumbnailRect.size.width  = targetSize.width;
   thumbnailRect.size.height = targetSize.height;
   [miniProfile drawInRect:thumbnailRect];
   tempImage = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();

   //Automatically change image to circle view
   UIImageView *roundProfile = [[UIImageView alloc] initWithImage:tempImage];
   roundProfile.backgroundColor = [UIColor clearColor];
   roundProfile.layer.cornerRadius = miniProfile.size.width/2;
   roundProfile.layer.masksToBounds = YES;
   [self.view addSubview: roundProfile];

   //Add image to navigation bar. However button cannot be clicked
   UIBarButtonItem * profileImage = [[UIBarButtonItem alloc] initWithCustomView:roundProfile];

   //Create two button on right navigation bar. One for image the other for real button
   NSArray *profilebarButton = @[profileImage];
   self.navigationItem.rightBarButtonItems = profilebarButton;

I able to put UIImageView in navigation bar, but i had 2 issues: 1.) If the image larger than 30x30 then the image won't appear, means the resize not work. 2.) I cannot click on image and need to create another button to handle this

Upvotes: 2

Views: 1393

Answers (1)

BHASKAR
BHASKAR

Reputation: 1201

You can use this code for custom navigation bar button

self.navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:UITextAttributeTextColor];

//create the button and assign the image
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:@"btn_next_arrow_01.png"] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:@"btn_next_arrow_02.png"] forState:UIControlStateHighlighted];
button.adjustsImageWhenDisabled = NO;


//set the frame of the button to the size of the image (see note below)
button.frame = CGRectMake(0, 0, 30, 30);

[button addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];

//create a UIBarButtonItem with the button as a custom view
UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.leftBarButtonItem = customBarItem;
self.navigationItem.hidesBackButton = YES;

Upvotes: 2

Related Questions