【发布时间】:2013-02-06 19:56:26
【问题描述】:
我是 iOS 开发的新手,我已经为此苦苦寻找解决方案大约一天了,但不知道为什么它不起作用。我正在尝试将视图控制器中的表格视图用作用户使用的小菜单。我已经检查了 NSArray 是否正在被填充,并且确实如此。我还检查了是否正在创建单元格,并且确实如此。我只是想不通为什么它没有用它创建的单元格填充表格视图。以下是我到目前为止的代码。提前感谢任何人都可以提供的任何帮助。
MainViewController.h
#import <UIKit/UIKit.h>
@interface MainViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *menuTableView;
@property (weak, nonatomic) IBOutlet UIButton *menuButton;
@property (strong, nonatomic) NSArray *menuItemsArray;
@property (weak, nonatomic) IBOutlet UILabel *menuLabel;
@end
MainViewController.m
#import "MainViewController.h"
@interface MainViewController ()
@end
@implementation MainViewController
@synthesize menuItemsArray, menuTableView, menuButton, menuLabel;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//Set TableView Delegate/DataSource to self
[self.menuTableView setDelegate:self];
[self.menuTableView setDataSource:self];
[self.menuTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
[self.menuTableView setBounces:NO];
[self.menuTableView setRowHeight:self.menuLabel.frame.size.height];
self.menuItemsArray = [[NSArray alloc] initWithObjects:@"Add Category", @"Add Item", @"Settings", nil];
NSLog(@"array: %@", menuItemsArray);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#pragma mark - UITableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return ([self.menuItemsArray count]);
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"menuCell"];
[[cell textLabel]setText:[self.menuItemsArray objectAtIndex:indexPath.row]];
[[cell textLabel]setFont:[self.menuLabel font]];
return cell;
}
-(void)tableView:(UITableView *)tableview didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[self.menuTableView deselectRowAtIndexPath:indexPath animated:YES];
NSString *selectedString = [self.menuItemsArray objectAtIndex:indexPath.row];
self.menuLabel.text = selectedString;
}
【问题讨论】:
-
行高设置为多少?
-
当前行高为44
-
你能用“现代”的Objective-C语法吗?使用越来越少的可读代码,这会更容易,例如: cell.textLabel.text = self.menuItemsArray[indexPath.row];检查 Xcode 菜单编辑 - 重构
-
在
-viewDidLoad的其余部分之后添加[self.menuTableView reloadData];会有所帮助吗? -
确保在您的 nib 文件中设置了表格视图的出口,否则无论如何您都不会将委托/数据源设置为表格。我也不确定设置行高的那行代码。
标签: ios uitableview tableview