【问题标题】:Insert UIImageView as navigation bar button插入 UIImageView 作为导航栏按钮
【发布时间】:2014-08-19 06:52:01
【问题描述】:

我是 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 放在导航栏中,但我遇到了 2 个问题: 1.) 如果图像大于 30x30,则图像不会出现,意味着调整大小不起作用。 2.) 我不能点击图片,需要创建另一个按钮来处理这个

【问题讨论】:

标签: objective-c button navigation uiimageview


【解决方案1】:

您可以将此代码用于自定义导航栏按钮

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    • 2017-06-25
    • 1970-01-01
    相关资源
    最近更新 更多