我想顯示圖像,標題名稱和兩個左右按鈕。我已經成功完成了。 下面是代碼:在導航欄上放置自定義視圖
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。視圖在導航欄上正確顯示,但在滾動tableview之後。最初它顯示在錯誤的座標上。
請建議。
您是否嘗試使自定義視圖的x座標不依賴於左側按鈕,例如20?那它有用嗎? (除了它不改變到按鈕寬度當然)爲什麼在'cellForRowAtIndexPath'? – tomsmeding 2012-08-09 06:58:28
需要在導航欄中顯示的數據是從數組中收集並取決於Tableview。 – Arvind 2012-08-09 08:43:46