iphone - 在导航栏上放置自定义 View

标签 iphone ios uinavigationbar

我想显示图像、标题名称和两个左右按钮。我已经成功完成了。 这是代码:

    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 200, 100)];

    UIButton *leftButton = [[UIButton alloc]init];
    [leftButton setImage:[UIImage imageNamed:@"previous-arrow.png"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(goPrevious:) forControlEvents:UIControlEventTouchUpInside];
    [leftButton setFrame:CGRectMake(20, 50, 14, 13)];

    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Title.png"]];
    [imageView setFrame:CGRectMake(leftButton.frame.origin.x+leftButton.frame.size.width+4, 20, 50, 50)];

    UILabel *nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(imageView.frame.origin.x+imageView.frame.size.width+4, 30, 100, 40)];
    NSString *cName = [NSString stringWithFormat:@"%@",[NameArray objectAtIndex:indexPath.section]];

    [nameLabel setTextColor:[UIColor whiteColor]];
    [nameLabel setBackgroundColor:[UIColor clearColor]];
    [nameLabel setContentMode:UIViewContentModeScaleAspectFill];
    [nameLabel setTextAlignment:UITextAlignmentLeft];
     CGSize expectedLabelSize = [cName sizeWithFont:nameLabel.font 
                                        constrainedToSize:CGSizeMake(100, 40) 
                                            lineBreakMode:nameLabel.lineBreakMode]; 
    [nameLabel setFrame:CGRectMake(imageView.frame.origin.x+imageView.frame.size.width+4, 35, expectedLabelSize.width, expectedLabelSize.height)];
    nameLabel.text=cName;

    UIButton *rightButton = [[UIButton alloc]init];
    [rightButton setImage:[UIImage imageNamed:@"next-arrow.png"] forState:UIControlStateNormal];
    [rightButton setFrame:CGRectMake(nameLabel.frame.origin.x+nameLabel.frame.size.width+4, 50, 14, 13)];
    [rightButton addTarget:self action:@selector(next:) forControlEvents:UIControlEventTouchUpInside];

    [view addSubview:nameLabel];
    [view addSubview:imageView];
    [view addSubview:leftButton];
    [view addSubview:rightButton];

    self.navigationItem.titleView = view; 

此代码写在 cellForRowAtIndexPath 中。该 View 在导航栏上正确显示,但在滚动 tableview 之后。最初它显示在错误的坐标上。

请建议。

最佳答案

将此代码放在viewWillAppearviewDidAppear 中。它不应该在 tableView 协议(protocol)中!

关于iphone - 在导航栏上放置自定义 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11878190/

相关文章:

iPhone超声波检测(超过22kHz)

iphone - 自定义书签图标添加到 UISearchBar

ios - Swift 2.0 中的自定义 PFQuery 和 PFObject 连接

ios - 从侧面菜单单击时,导航栏未填充在状态栏下?

iphone - 允许 UIBarButtonItem 触摸 UINavigationBar 的顶部和底部

iphone - 在此代码中何处释放CFStringRef

iphone - 导航栏 "back"关闭模态视图的按钮

ios - 在 Swift 中访问静态 Objective-C 方法

ios - 内存泄漏,多个 UIViewControllers 的其他问题

iphone - 导航栏自定义高度