我是Xcode和objective-c的新手,我尝试制作一个应用程序,导航菜单可以显示保存在MySQL数据库中的所有者的个人资料图片。我用导航栏按钮但似乎不能使用UIViewImage作为按钮。这是我的代码:
//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;
我能够将UIImageView放在导航栏中,但我遇到了两个问题: 1.)如果图像大于30x30,则图像不会出现,表示调整大小不起作用。 2.)我无法点击图片,需要创建另一个按钮来处理这个
答案 0 :(得分:2)
您可以将此代码用于自定义导航栏按钮
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;