将UIImageView添加到UINavigation栏而不是导航控制器中

时间:2015-08-06 04:25:37

标签: ios swift uiimageview uinavigationbar

我以模态方式呈现包含导航栏的视图控制器。此视图控制器未嵌入导航控制器中。我没有titleView可用或导航控制器中的其他东西用于此目的。界面构建器似乎也不允许我将UIImageView拖放到UINavigationBar上是否有一种简单的方法来添加它并将图像视图置于UINavigationBar的中间?

3 个答案:

答案 0 :(得分:0)

使用以下代码为控制器提供导航控制器。

YourViewController *viewController = [[YourViewController alloc] init];
UINavigationController *navController = [[UINavigationController alloc] viewController];
[self presentViewController:navController animated:TRUE completion:^{  }];

然后在YourViewController.mviewDidLoad()

self.navigationItem.titleView = [self setImageInTitleOfbar:@"imagename.png"];

实施此方法,

- (UIView *)setImageInTitleOfbar:(NSString *)imageName
{
    UIImageView *imgLogo = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 32)];
    imgLogo.image = [UIImage imageNamed:imageName];
    return imgLogo;

    /*UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, -5, 160, 35)];
    [view setBackgroundColor:[UIColor clearColor]];
    imgLogo.frame = CGRectMake(3, 0, view.frame.size.width-6, view.frame.size.height);
    [view addSubview:imgLogo];
    return view;*/
} 

答案 1 :(得分:0)

@ zig10,

这是在TitleView 中的UINavigation Bar中设置uiimageview的解决方案。

        self.navigationItem.titleView=nil;
        UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 200, 44)];
        img.backgroundColor=ColorClear;
        img.tag=101010;
        self.navigationItem.titleView = img;

我还使用以下代码在UiNavigation Bar中设置了UITextField,可能对您有所帮助

 tfNavTitle = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, 200, 44)];
        tfNavTitle.backgroundColor=ColorClear;
        tfNavTitle.clearsOnBeginEditing=YES;
        tfNavTitle.clearButtonMode=UITextFieldViewModeAlways;
        tfNavTitle.font = [UIFont boldSystemFontOfSize:19];
        tfNavTitle.textColor = ColorWhite;
        tfNavTitle.textAlignment = NSTextAlignmentLeft;
        tfNavTitle.delegate=self;
        tfNavTitle.tag=101010;
        [tfNavTitle becomeFirstResponder];

        tfNavTitle.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Search" attributes:@{NSForegroundColorAttributeName: ColorWhite}];

        //Set Animation
        [tfNavTitle.layer addAnimation:[ApplicationDelegate AnimateFromRight] forKey:nil];

        self.navigationItem.titleView = tfNavTitle;

答案 2 :(得分:0)

由于您未titleView添加Navigation Bar,因此您无法Navigation Item Navigation Bar

  1. 添加Navigation Bar
  2. Navigation Item添加到Navigation Bar
  3. 创建IBOutlet
  4. Navigation Item
  5. UIImageView设为navigationItem
  6. 示例

    @IBOutlet var navitaionBarItem: UINavigationItem!
    override func viewDidLoad() {
        super.viewDidLoad()
    
        self.navitaionBarItem.titleView = UIImageView(image: UIImage(named: "sample.png"))
    }