iOS 7 自定义单元格未显示在表格视图中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21048992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 23:04:29  来源:igfitidea点击:

iOS 7 custom cell not displaying in table view

iosobjective-cstoryboard

提问by c11ada

Please bear with me, I am just starting iOS development. I am trying to display a custom tableViewCellwithin a storyboard tableView. I have done the following.

请耐心等待,我刚刚开始iOS开发。我正在尝试tableViewCell在 storyboard 中显示自定义tableView。我做了以下工作。

I have created a new .xibwith a tableViewCellin it

我创建了一个新的.xibtableViewCell

enter image description here

在此处输入图片说明

I have then created a custom class for this. the .h file looks like this

然后我为此创建了一个自定义类。.h 文件看起来像这样

#import <UIKit/UIKit.h>

@interface CustomTableCell : UITableViewCell

@property (weak, nonatomic) IBOutlet UIImageView *thumbnailImageView;
@property (weak, nonatomic) IBOutlet UILabel? *titleLabel;

@end

Then in my TableViewController.mI have imported the CustomTableCell.hand I am doing following for 10 rows

然后在我的TableViewController.m导入中CustomTableCell.h,我正在执行 10 行

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CustomTableCell";
    CustomTableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if(cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomTableCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }

    cell.titleLabel.text ="test text";


    return cell;
}

This seems fine to build, but when the project loads nothing happens. Any advice will be great.

这看起来很好构建,但是当项目加载时什么也没有发生。任何建议都会很棒。

I have placed a breakpoint in the cellForRowAtIndexPathmethod, however it never reaches this point. here is a screen shot of the simulator

我在该cellForRowAtIndexPath方法中放置了一个断点,但它从未达到这一点。这是模拟器的屏幕截图

enter image description here

在此处输入图片说明

回答by Steve

You must register your .xibfile. In your viewDidLoadmethod, add the following:

您必须注册您的.xib文件。在您的viewDidLoad方法中,添加以下内容:

[self.tableView registerNib:[UINib nibWithNibName:@"CustomTableCell" bundle:nil] 
     forCellReuseIdentifier:@"CustomTableCell"];

回答by matt

The way you are loading the nib is really old-fashioned and outdated. It is much better (since iOS 6) to register the nib and use dequeueReusableCellWithIdentifier:forIndexPath:.

您加载笔尖的方式确实过时且过时。注册笔尖并使用dequeueReusableCellWithIdentifier:forIndexPath:.

See my explanationof all four ways of getting a custom cell.

请参阅我对获取自定义单元格的所有四种方法的解释

回答by Andy Obusek

Ensure that the delegate and datasource are set in the storyboard for the UITableView. This will ensure that cellForRowAtIndexPathis getting called for each row. You can put an NSLogmessage in that method to verify the same thing.

确保在 UITableView 的故事板中设置了委托和数据源。这将确保cellForRowAtIndexPath为每一行调用。您可以NSLog在该方法中放置一条消息来验证相同的内容。

Also, since you are using a storyboard, you may want to look into Prototype Cells for the UITableView. They are a much easier way of doing the same thing - creating a UITableView with custom cells.

此外,由于您使用的是故事板,您可能需要查看 UITableView 的原型单元格。它们是做同样事情的更简单的方法 - 创建带有自定义单元格的 UITableView。

Here's a decent tutorial on using Prototype cells within your storyboard's UITableView:

这是一个关于在故事板的 UITableView 中使用 Prototype 单元格的不错的教程:

http://www.raywenderlich.com/5138/beginning-storyboards-in-ios-5-part-1

http://www.raywenderlich.com/5138/beginning-storyboards-in-ios-5-part-1

回答by Melih Büyükbayram

- (void) viewDidLoad {

    [super viewDidLoad];

    UINib *cellNib = [UINib nibWithNibName:@"CustomTableCell" bundle:[NSBundle mainBundle]];
    [self.tableView registerNib:cellNib forCellReuseIdentifier:@"CustomTableCell"];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CustomTableCell";
    CustomTableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if(cell == nil)
    {
        cell = [[CustomTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    cell.titleLabel.text ="test text";


    return cell;
}

回答by Forrest

A very basic question, but have you implemented the tableview delegate method that indicates how many cells should be displayed? The delegate method is the following:

一个非常基本的问题,但是您是否实现了指示应显示多少个单元格的 tableview 委托方法?委托方法如下:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //Return number of cells to display here
    return 1;
}

回答by Jakikiller

Be sure to have only one item in your xib (Uitableviewcell instance)

确保您的 xib 中只有一项(Uitableviewcell 实例)

回答by deepa

#import <UIKit/UIKit.h>
#import "DetailViewController.h"
#import "NewViewController.h"
#import "CustomCellVC.h"

@interface FirstVC : UIViewController
{
    DetailViewController *detailViewController;
    NewViewController *objNewViewController;
    CustomCellVC *objCustom;
    NSMutableData *webData;
    NSArray *resultArray;
    //IBOutlet UIButton *objButton;
}
@property(strong,nonatomic)IBOutlet DetailViewController *detailViewController;
@property(strong,nonatomic)IBOutlet UITableView *objTable;
-(void)loginWS;
-(IBAction)NewFeatureButtonClk:(id)sender;
@end

#import "FirstVC.h"

@interface FirstVC ()

@end

@implementation FirstVC
@synthesize objTable;
@synthesize detailViewController;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    objTable.frame = CGRectMake(0, 20, 320, 548);
    [self loginWS];
}
-(void)loginWS
{
    //Para username password
    NSURL *url = [NSURL URLWithString:@"http://192.168.0.100/FeatureRequestComponent/FeatureRequestComponentAPI"];
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
    [req setHTTPMethod:@"POST"];
    [req addValue:@"application/json"  forHTTPHeaderField:@"Content-Type"];
   // [req addValue:[NSString stringWithFormat:@"%i",postBody.length] forHTTPHeaderField:@"Content-Length"];
    [req setTimeoutInterval:60.0 ];
    //[req setHTTPBody:postBody];
    //[cell setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"CellBg.png"]]];

    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:req delegate:self];

    if (connection)
    {
        webData = [[NSMutableData alloc]init];
    }

}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [webData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [webData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
    resultArray = [[NSArray alloc]initWithArray:[responseDict valueForKey:@"city"]];
    NSLog(@"resultArray: %@",resultArray);
    [self.objTable reloadData];
}
-(IBAction)NewFeatureButtonClk:(id)sender
{
    objNewViewController=[[NewViewController alloc]initWithNibName:@"NewViewController" bundle:nil];
    // Push the view controller.
    [self.navigationController pushViewController:objNewViewController animated:YES];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return [resultArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
   objCustom = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (objCustom == nil) {
       objCustom = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }


   //objCustom.persnName.text=[[resultArray objectAtIndex:indexPath.row]valueForKey:@"Name"];
    //objCustom.persnAge.text=[[resultArray objectAtIndex:indexPath.row]valueForKey:@"Age"];


   // Configure the cell...
    objCustom.textLabel.text = [[resultArray objectAtIndex:indexPath.row] valueForKey:@"FeatureTitle"];
    objCustom.detailTextLabel.text = [[resultArray objectAtIndex:indexPath.row] valueForKey:@"Description"];


    return objCustom;
}

#pragma mark - Table view delegate

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here, for example:
    // Create the next view controller.
    detailViewController = [[DetailViewController alloc]initWithNibName:@"DetailViewController" bundle:nil];
    detailViewController.objData=[resultArray objectAtIndex:indexPath.row];
    // Pass the selected object to the new view controller.

    // Push the view controller.
    [self.navigationController pushViewController:detailViewController animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
#import <UIKit/UIKit.h>
#import "DetailData.h"

@interface DetailViewController : UIViewController
{
    DetailData *objData;
}
@property(strong,nonatomic)IBOutlet UITextField *usecaseTF;
@property(strong,nonatomic)IBOutlet UITextView *featureTF;
@property(strong,nonatomic)IBOutlet UILabel *priority;
@property(strong,nonatomic)IBOutlet UIButton *voteBtn;
@property(strong,nonatomic)IBOutlet DetailData *objData;
-(IBAction)voteBtnClk:(id)sender;
@end
#import "DetailViewController.h"

@interface DetailViewController ()

@end

@implementation DetailViewController
@synthesize objData,usecaseTF,featureTF,priority,voteBtn;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    usecaseTF.text=objData.usecaseTF;
    featureTF.text=objData.featureTF;
    priority.text=objData.priority;


}

-(IBAction)voteBtnClk:(id)sender
{
    if ([voteBtn.currentImage isEqual:@"BtnGreen.png"])
    {
        [voteBtn setImage:[UIImage imageNamed:@"BtnBlack.png"] forState:UIControlStateNormal];
    }
    else
    {
        [voteBtn setImage:[UIImage imageNamed:@"BtnGreen.png"] forState:UIControlStateNormal];

    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

#import <UIKit/UIKit.h>

@interface NewViewController : UIViewController<UITextFieldDelegate>
{
    UITextField *currentTF;
}
@property(strong,nonatomic) IBOutlet UITextField *nameTF;
@property(strong,nonatomic)IBOutlet UITextField *emailTF;
@property(strong,nonatomic)IBOutlet UITextField *featureTF;
@property(strong,nonatomic)IBOutlet UITextField *descpTF;
@property(strong,nonatomic)IBOutlet UITextView *UsecaseTV;
@property(strong,nonatomic)IBOutlet UIButton *HighBtn;
@property(strong,nonatomic)IBOutlet UIButton *LowBtn;
@property(strong,nonatomic)IBOutlet UIButton *MediumBtn;

-(IBAction)sendRequestBtnClk:(id)sender;
-(IBAction)RadioBtnHigh:(id)sender;
-(IBAction)RadioBtnLow:(id)sender;
-(IBAction)RadioBtnMedium:(id)sender;
-(void)radioBtnClick;
@end
#import "NewViewController.h"

@interface NewViewController ()

@end

@implementation NewViewController

@synthesize nameTF,emailTF,featureTF,descpTF,UsecaseTV,LowBtn,HighBtn,MediumBtn;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title=@"Did I Know This";
    currentTF=[[UITextField alloc]init];
    [ self radioBtnClick];
}

-(IBAction)sendRequestBtnClk:(id)sender
{

    if (nameTF.text.length==0)
    {
        [self showAlertMessage:@"Please enter Your Name"];
        //  return NO;
    }
    else if (emailTF.text.length==0)
    {
        [self showAlertMessage:@"Please enter email ID"];

    }
    if (emailTF.text.length==0)
    {
        [self showAlertMessage:@"Please enter email address"];

    }
    else if ([self emailValidation:emailTF.text]==NO)
    {
        [self showAlertMessage:@"Please enter valid email address"];

    }
    else if(featureTF.text.length==0)
    {
    [self showAlertMessage:@"Please Confirm the Feature title"];
    }

}
-(BOOL) emailValidation:(NSString *)emailTxt
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:emailTxt];

}

-(void)showAlertMessage:(NSString *)msg
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Note" message:msg delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
    [alert show];
}

 #pragma mark TextField Delegates
 - (BOOL)textFieldShouldReturn:(UITextField *)textField
 {
  [currentTF resignFirstResponder];

 return YES;
 }
 -(void)textFieldDidBeginEditing:(UITextField *)textField
 {
 currentTF = textField;
 [self animateTextField:textField up:YES];
 }

 - (void)textFieldDidEndEditing:(UITextField *)textField
 {
 currentTF = textField;

 [self animateTextField:textField up:NO];
 }

 -(void)animateTextField:(UITextField*)textField up:(BOOL)up
 {
 int movementDistance = 0; // tweak as needed

 if (textField.tag==103||textField.tag==104||textField.tag==105||textField.tag==106)
 {
 movementDistance = -130;
 }

 else if (textField.tag==107||textField.tag==108)
 {
 movementDistance = -230;
 }
 else
 {
 movementDistance = 00;

 }
 const float movementDuration = 0.3f; // tweak as needed

 int movement = (up ? movementDistance : -movementDistance);

 [UIView beginAnimations: @"animateTextField" context: nil];
 [UIView setAnimationBeginsFromCurrentState: YES];
 [UIView setAnimationDuration: movementDuration];
 self.view.frame = CGRectOffset(self.view.frame, 0, movement);
 [UIView commitAnimations];
 }

 -(void)radioBtnClick
 {
     if ([HighBtn.currentImage isEqual:@"radiobutton-checked.png"])
     {


      [LowBtn setImage:[UIImage imageNamed:@"radiobutton-checked.png"] forState:UIControlStateNormal];
    [MediumBtn setImage:[UIImage imageNamed:@"radiobutton-unchecked.png"] forState:UIControlStateNormal];
      [HighBtn setImage:[UIImage imageNamed:@"radiobutton-unchecked.png"] forState:UIControlStateNormal];
     }
     else
     {
         [LowBtn setImage:[UIImage imageNamed:@"radiobutton-unchecked.png"] forState:UIControlStateNormal];
         [HighBtn setImage:[UIImage imageNamed:@"radiobutton-checked.png"] forState:UIControlStateNormal];
        [MediumBtn setImage:[UIImage imageNamed:@"radiobutton-unchecked.png"] forState:UIControlStateNormal];
     }
 }

-(IBAction)RadioBtnHigh:(id)sender
 {


        [LowBtn setImage:[UIImage imageNamed:@"radiobutton-checked.png"] forState:UIControlStateNormal];
        [HighBtn setImage:[UIImage imageNamed:@"radiobutton-unchecked.png"] forState:UIControlStateNormal];
     [MediumBtn setImage:[UIImage imageNamed:@"radiobutton-unchecked.png"] forState:UIControlStateNormal];
 }


-(IBAction)RadioBtnLow:(id)sender
 {


    [LowBtn setImage:[UIImage imageNamed:@"radiobutton-unchecked.png"] forState:UIControlStateNormal];
    [HighBtn setImage:[UIImage imageNamed:@"radiobutton-checked.png"] forState:UIControlStateNormal];
     [MediumBtn setImage:[UIImage imageNamed:@"radiobutton-unchecked.png"] forState:UIControlStateNormal];

 }
-(IBAction)RadioBtnMedium:(id)sender
{
    [LowBtn setImage:[UIImage imageNamed:@"radiobutton-unchecked.png"] forState:UIControlStateNormal];
    [HighBtn setImage:[UIImage imageNamed:@"radiobutton-unchecked.png"] forState:UIControlStateNormal];
    [MediumBtn setImage:[UIImage imageNamed:@"radiobutton-checked.png"] forState:UIControlStateNormal];
}





- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
#import <UIKit/UIKit.h>

@interface CustomCellVC : UITableViewCell
@property (strong,nonatomic) IBOutlet UIImageView *persnImage;
@property (strong,nonatomic) IBOutlet UIButton *thumbImage;
@property (strong,nonatomic) IBOutlet UIImageView *calenderImage;
@property (strong,nonatomic) IBOutlet UIButton *voteImage;
@property (strong,nonatomic) IBOutlet UIButton *selectImage;
@property (strong,nonatomic) IBOutlet UILabel *publabel;
@property (strong,nonatomic) IBOutlet UILabel *IdLabel;
@property (strong,nonatomic) IBOutlet UILabel *decpLabel;
@property (strong,nonatomic) IBOutlet UITextField *ansTF;


@end
#import "CustomCellVC.h"

@implementation CustomCellVC
@synthesize ansTF,persnImage,publabel,thumbImage,calenderImage,voteImage,selectImage,IdLabel,decpLabel;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
@synthesize ObjFirstVC,objNavc;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    ObjFirstVC=[[FirstVC alloc ]initWithNibName:@"FirstVC" bundle:nil];
    objNavc=[[UINavigationController alloc]initWithRootViewController:ObjFirstVC];
    [self.window addSubview:objNavc.view];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

#import <Foundation/Foundation.h>

@interface DetailData : NSObject
@property(strong,nonatomic)IBOutlet UITextField *usecaseTF;
@property(strong,nonatomic)IBOutlet UITextView *featureTF;
@property(strong,nonatomic)IBOutlet UILabel *priority;
@property(strong,nonatomic)IBOutlet UIButton *voteBtn;
@end