UIImageView background color but not image displaying - ios

I have a UITableViewCell nib file in which there is a UIImageView and a UILabel. I have outlets for both of these to my controller as well as an outlet for the cell itself. I am setting the label and image programmatically, but the image does not show up.
So I went to test it, and even if I set the image itself in the nib file, it does not show up. If I set the background color, it shows up fine. Any ideas? I'm stuck.
It seems to be unrelated to code, in my mind, since it doesn't even work via nib file. But here it is anyway in case it helps somehow.
MyViewController.h
#interface MyViewController : UITableViewController
#property (strong, nonatomic) MyModel *myModel;
#property (strong, nonatomic) NSArray *tableViewCells;
#property (strong, nonatomic) IBOutlet UITableViewCell *tableViewCell;
#property (weak, nonatomic) IBOutlet UILabel *myLabel;
#property (weak, nonatomic) IBOutlet UIImageView *myImage;
#end
MyViewController.m
#interface MyViewController ()
- (void)bindMyModel:(MyModel*)model toView:(UITableViewCell*)view;
- (UITableViewCell*)copyUITableViewCell:(UITableViewCell*)cell;
#end
#implementation MenuViewController
#synthesize myModel = _myModel;
#synthesize tableViewCells = _tableViewCells;
#synthesize tableViewCell = _tableViewCell;
#synthesize myLabel = _myLabel;
#synthesize myImage = _myImage;
- (void)viewDidLoad
{
[super viewDidLoad];
NSMutableArray *cells = [[NSMutableArray alloc] init];
[MyModel loadAndOnSuccess:^(id data, id context) {
self.myModel = data;
for (MyModel *item in self.myModel.items) {
[[NSBundle mainBundle] loadNibNamed:#"TableCellNib" owner:self options:nil];
[self bindMyModel:item toView:self.tableViewCell];
[cells addObject:[self copyUITableViewCell:self.tableViewCell]];
self.tableViewCell = nil;
}
self.tableViewCells = [[NSArray alloc] initWithArray:cells];
} onFail:^(NSString *error, id context) {
NSLog(#"FAIL with error: %#", error);
}];
}
- (void)viewDidUnload
{
[self setTableViewCell:nil];
[self setMyLabel:nil];
[self setMyImage:nil];
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
- (void) bindMyModel:(MyModel*)model toView:(UITableViewCell*)view
{
if (view) {
self.myLabel.text = model.myLabelText;
self.myImage.image = model.myImageResource;
self.myLabel = nil;
self.myImage = nil;
}
}
- (UITableViewCell*)copyUITableViewCell:(UITableViewCell*)cell
{
NSData *archivedData = [NSKeyedArchiver archivedDataWithRootObject: cell];
return [NSKeyedUnarchiver unarchiveObjectWithData: archivedData];
}
#pragma mark - Table view data source
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
return [self.tableViewCells objectAtIndex:indexPath.row];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.myModel.items.count;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Irrelevant code here
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return ((UITableViewCell*)[self.tableViewCells objectAtIndex:indexPath.row]).frame.size.height;
}
#end

You are trying to use two IBOutlets on your UITableViewController to populate a multitude of UILabels and UIImageViews that are part of the UITableViewCell. You need to create a custom subclass of UITableViewCell and add the IBOutlets to that subclass.
#interface CustomCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UILabel *myLabel;
#property (weak, nonatomic) IBOutlet UIImageView *myImage;
#end
then in your bindMyModel:toView:
- (void) bindMyModel:(MyModel*)model toView:(CustomCell*)view
{
if (view) {
view.myLabel.text = model.myLabelText;
view.myImage.image = model.myImageResource;
}
}
Now you have independent IBOutlets for each of your Cells. You will also need to change some of your bindings as well. This is a fix, but honestly I would rewrite a lot of the code and just use dequeueReusableCellWithIdentifier in your cellForRowAtIndexPath call, and keep a pool of CustomCells that you will reuse, and just set up the myLabel.text and myImage.image in the cellForRowAtIndexPath call.

Related

Why my tableView stretch out?

I create a LMLUpspringChoosePeriodView and on it there is a tableView and a backgroundView,
I can use the LMLUpspringChoosePeriodView as the popup View, in my project.
This is the directory of it:
the LMLUpspringChoosePeriodView have ChoosePeriodTableViewHeader and LMLUpspringPeriodCell, all of them I create a XIB:
And In the LMLUpspringPeriodCell, I add the constraints to the name label, so it must be on the centre of the LMLUpspringPeriodCell:
But however, when I show the LMLUpspringChoosePeriodView as popup view, there comes an issue:
The tableView seems strech out of the screen.
My tableView's constraints is like this:
My code is below:
LMLUpspringChoosePeriodView.h:
typedef void(^LMLUpspringBlock)();
#import <UIKit/UIKit.h>
#interface LMLUpspringChoosePeriodView : UIView
#property (weak, nonatomic) IBOutlet UIView *upspringBackView;
#property (weak, nonatomic) IBOutlet UITableView *tableView;
#property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottom_tableView;
#property (nonatomic, copy) LMLUpspringBlock block;
- (void)showSelf;
- (void)hideSelf;
#end
LMLUpspringChoosePeriodView.m:
#import "LMLUpspringChoosePeriodView.h"
#import "LMLUpspringPeriodCell.h"
#import "ChoosePeriodTableViewHeader.h"
#interface LMLUpspringChoosePeriodView () <UITableViewDelegate, UITableViewDataSource>
#property (weak, nonatomic) IBOutlet NSLayoutConstraint *width_tableView;
#property (nonatomic, strong) NSArray *title_arr;
#end
#implementation LMLUpspringChoosePeriodView
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
- (void)awakeFromNib {
[super awakeFromNib];
//_width_tableView.constant = KWidth;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 4;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
ChoosePeriodTableViewHeader *header = [[NSBundle mainBundle] loadNibNamed:#"ChoosePeriodTableViewHeader" owner:self options:nil].firstObject;
header.cancel_block = ^() {
[self hideSelf];
};
return header;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
LMLUpspringPeriodCell *cell = [tableView dequeueReusableCellWithIdentifier:#"LMLUpspringPeriodCell"];
if (cell == nil) {
cell = [[NSBundle mainBundle] loadNibNamed:#"LMLUpspringPeriodCell" owner:self options:nil].firstObject;
}
// 配置cell
cell.title_label.text = self.title_arr[indexPath.row];
if (indexPath.row == 3) {
cell.bottom_line.hidden = YES;
}
[self setNeedsLayout];
[self layoutIfNeeded];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 44;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 48;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
LMLUpspringPeriodCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSString *period_str = cell.title_label.text;
self.block(period_str);
[self hideSelf];
}
#pragma mark - action
- (void)showSelf {
self.hidden = NO;
[UIView animateWithDuration:0.5 animations:^{
_bottom_tableView.constant = -49;
_upspringBackView.alpha = 0.3f;
}];
}
- (void)hideSelf {
_bottom_tableView.constant = -_tableView.bounds.size.height - 49;
[UIView animateWithDuration:0.25 animations:^{
_upspringBackView.alpha = 0.f;
[self layoutIfNeeded];
} completion:^(BOOL finished) {
if (finished) {
self.hidden = YES;
}
}];
}
- (IBAction)tapBackView:(id)sender {
[self hideSelf];
}
#pragma mark - setter
-(NSArray *)title_arr {
if (!_title_arr) {
_title_arr = #[#"当天", #"最近一周", #"最近一个月", #"最近三个月"];
}
return _title_arr;
}
#end
The ChoosePeriodTableViewHeader.h:
#import <UIKit/UIKit.h>
typedef void(^CancelChooseUpspringView)();
#interface ChoosePeriodTableViewHeader : UIView
#property (nonatomic, copy) CancelChooseUpspringView cancel_block;
#end
The ChoosePeriodTableViewHeader.m:
#import "ChoosePeriodTableViewHeader.h"
#implementation ChoosePeriodTableViewHeader
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
// 取消
- (IBAction)cancel:(UIButton *)sender {
self.cancel_block();
}
The LMLUpspringPeriodCell.h:
#import <UIKit/UIKit.h>
typedef void(^ConfirmChoosePeriod)(NSString *);
#interface LMLUpspringPeriodCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UILabel *title_label;
#property (weak, nonatomic) IBOutlet UIView *bottom_line;
#property (nonatomic, copy) ConfirmChoosePeriod confirm_block;
#end
The LMLUpspringPeriodCell.m:
#import "LMLUpspringPeriodCell.h"
#implementation LMLUpspringPeriodCell
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
#end
I have tried use the below code in the awakeFromNib method in the LMLUpspringChoosePeriodView.m(you can see the LMLUpspringChoosePeriodView.m code, there is annotation in the awakeFromNib method ):
_width_tableView.constant = KWidth;
Replace of the tableView using trailling to constraint the tableView, it still strech out, but use the below code :
_width_tableView.constant = KWidth / 2;
It is perfect in iPhone7, but have issue in iPhone7 Plus:
So, it is a very strange issue here, how to do with that?
Not enough, there is second issue, the last item can not click, I don't know if is related to the tabbar.
How to solve the two issue? Thanks in advance.
EDIT -1
I add the LMLUpspringChoosePeriodView to the kwyWindow on a VC:
#property (nonatomic, strong) LMLUpspringChoosePeriodView *upspring_v;
....
[[UIApplication sharedApplication].keyWindow addSubview:self.upspring_v];
EDIT -2
This is my PurchaseRecordVC.m, in there I show the LMLUpspringChoosePeriodView:
#import "PurchaseRecordVC.h"
#import "LMLUpspringChoosePeriodView.h"
#interface PurchaseRecordVC ()
#property (nonatomic, strong) LMLUpspringChoosePeriodView *upspring_v;
#end
#implementation PurchaseRecordVC
- (void)viewDidLoad {
[super viewDidLoad];
[self initData];
[self initUI];
}
#pragma mark - init
- (void)initData {
}
- (void)initUI {
// 添加界面
[[UIApplication sharedApplication].keyWindow addSubview:self.upspring_v];
}
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
- (IBAction)clickTheChoosePeriod:(UIButton *)sender {
[_upspring_v showSelf];
}
#pragma mark - getter
- (LMLUpspringChoosePeriodView *)upspring_v {
if (!_upspring_v) {
_upspring_v = [[NSBundle mainBundle] loadNibNamed:#"LMLUpspringChoosePeriodView" owner:self options:nil].firstObject;
// 初始化
_upspring_v.upspringBackView.alpha = 0;
_upspring_v.bottom_tableView.constant = -_upspring_v.tableView.bounds.size.height - 49;
_upspring_v.hidden = YES;
_upspring_v.block = ^(NSString *period){
};
}
return _upspring_v;
}
#pragma mark - dealloc
- (void)dealloc {
// 移除界面
[self.upspring_v removeFromSuperview];
}
#end
I created a playground satisfying the same conditions, but altered it a bit for you to use as an example
Here you go:
https://wetransfer.com/downloads/7cf7267e51b7d265204a3ceaed48d0fd20170424125153/c92374

How do I get this UITableView to display?

I can't figure out how to get this UITableView to display.
The code creates the table fully programmatically except for the nib.
The nib is a simple cell that works in other UITableViews in the same app.
When the table view is created and added as a subview to the view and reloadData is called then numberOfSectionsInTableView: and tableView:numberOfRowsInSection: are both called. They both return 1. (I checked in the debugger.)
However tableView:cellForRowAtIndexPath: is never called.
I add the tableView to it's parent view with a NSLayoutConstraint that forces it's height, but nothing is displayed in that spot.
The view hierarchy debugger shows nothing in that spot and that there isn't a view on top of the table.
The app runs without any error or crashes.
I would appreciate your help.
#interface MyViewCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UIButton *button;
#end
#implementation MyViewCell
#end
#interface MyDataTableEntry : NSObject
#property (nonatomic, strong) NSString* title;
#end
#implementation MyDataTableEntry
#end
#interface MyDataTable : NSObject <UITableViewDataSource, UITableViewDelegate>
#property (strong, nonatomic) UITableView *tableView;
#property (strong, nonatomic) NSArray *rows;
#property (strong, nonatomic) UINib* nib;
#end
#implementation MyDataTable
- (UINib*)getAndRegisterNib:(NSString*)reuseIdentifier {
UINib* nib = [UINib nibWithNibName:reuseIdentifier bundle:nil];
[self.tableView registerNib:nib forCellReuseIdentifier:reuseIdentifier];
return nib;
}
- (id)initWithRows:(NSArray*) rows andView:(UIView*)view {
if (self = [super init]) {
self.rows = rows;
self.tableView = [[UITableView alloc] initWithFrame:view.bounds style:UITableViewStylePlain];
self.nib = [self getAndRegisterNib:#"PrototypeCell"];
self.tableView.delegate = self;
self.tableView.dataSource = self;
self.tableView.backgroundColor = [UIColor grayColor];
}
return self;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.rows.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MyViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"PrototypeCell" forIndexPath:indexPath];
MyDataTableEntry* entry = self.rows[indexPath.row];
[cell.button setTitle:entry.name forState:UIControlStateNormal];
cell.button.backgroundColor = [UIColor blueColor];
return cell;
}
#end
Here is a snippet that creates the table:
MyDataTableEntry* entry = [[MyDataTableEntry alloc] init];
entry.title = #"hello";
self.dataTable = [[MyDataTable alloc] initWithRows:#[entry] andView:self.view];
[self.view addSubview:self.dataTable.tableView];
[self.dataTable.tableView setNeedsLayout];
[self.dataTable.tableView layoutIfNeeded];
[self.dataTable.tableView reloadData];
Without confirming in a debugger:
The problem is here:
self.dataTable = [[MyDataTable alloc] initWithRows:#[entry] andView:self.view];
[self.view addSubview:self.dataTable];
self.dataTable is an NSObject. The second line should read something like this:
[self.view addSubview:self.dataTable.tableView];
I would also suggest that you engage in some refactoring. MyDataTable is not a view. It's a controller. So rename to MyDataTableController. Then the bug would have been more obvious.
I would also ask why you are doing this in code? you are already using nibs. So why not go to storyboards. Doing that and using UITableViewController as a base class should enable you to remove a lot of the code and potential bugs.

Unexpected delay when presenting UITableViewController

I have a custom UITableViewCell in a UITableViewController, but when the Controller tries to dequeue the custom cell, it will take a long time (like 2000ms).
This line of code causes the problem
KidsListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"kidsReuseIdentifier" forIndexPath:indexPath];
The KidsListTableViewCell is a custom cell, which includes couple of UIButtons, some UILabels to show the information. And two delegate methods. It shouldn't be that slow to render that view. By the way, all of the information in the custom cell is basically static.
The is the full code of the UITableViewController. I put the custom view and regular view in different sections and I don't think this causes the problem.
#import "KidDetailTableViewController.h"
#import "KidDetailHeaderTableViewCell.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "Helper.h"
#interface KidDetailTableViewController () <KidDetailHeaderCellDelegate>
#end
#implementation KidDetailTableViewController
{
KidDetailHeaderTableViewCell *headerCell;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self.tableView registerNib:[UINib nibWithNibName:#"KidDetailHeader" bundle:nil] forCellReuseIdentifier:#"kidDetail"];
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"detailCell"];
self.tableView.showsVerticalScrollIndicator = NO;
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
switch (section) {
case 0:
return 1;
break;
default:
return 10;
break;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.section == 0) {
if (!headerCell) {
headerCell = [tableView dequeueReusableCellWithIdentifier:#"kidDetail"];
headerCell.delegate = self;
// Keep the background color for the cell when select.
headerCell.selectionStyle = UITableViewCellSelectionStyleNone;
headerCell.nicknameLabel.text = _kidNeedsToShow.nickname;
NSString *kidFullName = [NSString stringWithFormat:#"%# %# %#", _kidNeedsToShow.firstName, _kidNeedsToShow.midName, _kidNeedsToShow.lastName];
kidFullName ? (headerCell.fullNameLabel.text = #"") : (headerCell.fullNameLabel.text = kidFullName);
// Set thumb image or use default
// if there isn't image, use default.
ALAssetsLibrary *library = [ALAssetsLibrary new];
[library assetForURL:_kidNeedsToShow.photoURL resultBlock:^(ALAsset *asset) {
[headerCell.avatarImage setImage:[UIImage imageWithCGImage:[[asset defaultRepresentation] fullResolutionImage]]];
} failureBlock:nil];
return headerCell;
}
else return headerCell;
}
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"detailCell" forIndexPath:indexPath];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.section == 0) {
return 290;
}
else return 60;
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.section == 0) {
return 290;
}
else return 60;
}
- (void)didClickLeftButton:(UIButton *)leftButton {
[self dismissViewControllerAnimated:YES completion:nil];
}
#end
I tried to put dequeueReusableCellWithIdentifier into a different thread, apparently it wouldn't work.
UPDATE: KidDetailHeaderTableViewCell.m
- (void)awakeFromNib {
// Initialization code
[_avatarImage.layer setCornerRadius:_avatarImage.frame.size.width / 2];
[_avatarImage.layer setBorderColor:[UIColor whiteColor].CGColor];
[_avatarImage.layer setBorderWidth:1.0];
[_avatarImage setClipsToBounds:YES];
}
- (IBAction)leftButtonClicked:(UIButton *)sender {
if (self.delegate && [self.delegate respondsToSelector:#selector(didClickLeftButton:)]) {
[self.delegate didClickLeftButton:sender];
}
}
- (IBAction)rightButtonClicked:(UIButton *)sender {
if (self.delegate && [self.delegate respondsToSelector:#selector(didClickRightButton:)]) {
[self.delegate didClickRightButton:sender];
}
}
KidDetailHeaderTableViewCell.h
#protocol KidDetailHeaderCellDelegate <NSObject>
#optional
- (void)didClickLeftButton:(UIButton *)leftButton;
- (void)didClickRightButton:(UIButton *)rightButton;
#end
#interface KidDetailHeaderTableViewCell : UITableViewCell
#property (weak) id<KidDetailHeaderCellDelegate> delegate;
#property (weak, nonatomic) IBOutlet UILabel *fullNameLabel;
#property (weak, nonatomic) IBOutlet UIImageView *avatarImage;
#property (weak, nonatomic) IBOutlet UILabel *nicknameLabel;
#property (weak, nonatomic) IBOutlet UILabel *ageText;
#property (weak, nonatomic) IBOutlet UILabel *ageLabel;
#property (weak, nonatomic) IBOutlet UILabel *momentsStatistics;
#property (weak, nonatomic) IBOutlet UILabel *momentsLabel;
#property (weak, nonatomic) IBOutlet UIButton *rightButton;
#property (weak, nonatomic) IBOutlet UIButton *leftButton;
#end
UPDATE 2:
screenshot of instrument
The code for set the height of the cell. I have two sections, the first section actually is only used for header, the height is 290.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.section == 0) {
return 290;
}
else return 60;
}
One of my friend pointed out that problem was caused by the custom font (Yes! I used custom font in the custom view). I still not sure about why this causes the problem (the font named 'hero'), but hope this will help someone else.

Add a push segue to a button inside of a custom cell of a tableview

I have a project that displays a feed of statuses similar to other social networks. Each feed item has several button that do different things. 1 of the buttons opens a new viewcontroller that displays the comments that have been posted on a particular status. When this button is clicked and the view controller is opened i would like it to be a push segue so that their is a back button and the user can navigate back to the feed.
When this button is clicked and the new vc is launched some unique data about the particular status/cell being clicked needs to be sent to the "comments vc ". Where would the code for doing this go?
CUSTOM CELL .H
#import <UIKit/UIKit.h>
#interface FeedItemCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UIImageView *DefaultImg;
#property (weak, nonatomic) IBOutlet UILabel *NameLabel;
#property (weak, nonatomic) IBOutlet UILabel *StatusLabel;
#property (weak, nonatomic) IBOutlet UILabel *timeLabel;
#property (nonatomic, copy) NSString *msg_id;
#property (nonatomic, copy) NSString *status;
#property (nonatomic, weak) IBOutlet UIButton* commentButton;
#property (nonatomic, weak) IBOutlet UIButton* bumpButton;
#property (strong, nonatomic) id delegate;
-(IBAction)viewComments:(id)sender;
-(IBAction)bump:(id)sender;
#end
#protocol CustomCellProtocol <NSObject>
- (void)EBCellPressed:(NSString *)cellName;
CUSTOM CELL .M
#import "FeedItemCell.h"
#import "CommentsViewController.h"
#import "NSDate+TimeAgo.h"
#interface FeedItemCell() <WYPopoverControllerDelegate>
{
}
- (IBAction)open:(id)sender;
- (void)close:(id)sender;
#end
#implementation FeedItemCell
#synthesize commentButton;
- (instancetype)initWithDelegate:(id)delegate {
self = [super init];
if (self) {
self.delegate = delegate;
// Initialization code
}
return self;
}
-(IBAction)bump:(id)sender{
[self.delegate EBCellPressed:#"NAME"];
}
- (IBAction)open:(id)sender
{
}
#end
publicFeed . M
#import "PublicFeedViewController.h"
#import "FeedItemCell.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "InboxDetailViewController.h"
#import "SWRevealViewController.h"
#import "CommentsViewController.h"
#import "NSDate+TimeAgo.h"
#interface PublicFeedViewController (){
NSArray *NameLabel;
NSArray *StatusLabel;
NSMutableArray *feedArray;
}
#end
#implementation PublicFeedViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//The below code prompts the user for push notifications. If allowed, code in AppDelegate takes over and stores the token.
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
// Do any additional setup after loading the view.
self.FeedTable.dataSource=self;
self.FeedTable.delegate=self;
// Set the side bar button action. When it's tapped, it'll show up the sidebar.
_sidebarButton.target = self.revealViewController;
_sidebarButton.action = #selector(revealToggle:);
// Set the gesture
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"foo": #"bar"};
[UIApplication sharedApplication].networkActivityIndicatorVisible = TRUE;
[manager POST:#"www" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
//NSLog(#"JSON: %#", responseObject);
self->feedArray = [responseObject objectForKey:#"feed"];
[self.FeedTable reloadData];
[UIApplication sharedApplication].networkActivityIndicatorVisible = FALSE;
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return feedArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *CellIdentifier=#"Cell";
FeedItemCell *Cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(!Cell){
Cell = [[FeedItemCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSLog(#"FEED ARRAY: %#", self->feedArray);
NSDictionary *tempDictionary= [self->feedArray objectAtIndex:indexPath.row];
// Display recipe in the table cell
NSString *thumb_img = [tempDictionary objectForKey:#"thumb_img"];
NSString *thumb_path=#"http://buhzhyve.com/CI_REST_LOGIN/UPLOADS/thumbs/";
NSString *thumb_url = [thumb_path stringByAppendingString:thumb_img];
Cell.NameLabel.text=[tempDictionary objectForKey:#"first_name"];
Cell.StatusLabel.text=[tempDictionary objectForKey:#"message"];
Cell.msg_id=[tempDictionary objectForKey:#"msg_id"];
//Cell.status=[tempDictionary objectForKey:#"message"];
Cell.StatusLabel.lineBreakMode=0;
Cell.StatusLabel.numberOfLines=0;
NSString *commentCount = [tempDictionary objectForKey:#"comment_count"];
NSString *commentButtonText =[NSString stringWithFormat:#"Comments ( %# )",commentCount];
[Cell.commentButton setTitle:commentButtonText forState: UIControlStateNormal];
NSString *bumpCount = [tempDictionary objectForKey:#"bump_count"];
NSString *bumpButtonText =[NSString stringWithFormat:#"Bumps ( %# )",bumpCount];
[Cell.bumpButton setTitle:bumpButtonText forState: UIControlStateNormal];
//[Cell.StatusLabel sizeToFit];
NSString *created_string=[tempDictionary objectForKey:#"created"];
double created_double = created_string.doubleValue;
NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:created_double];
NSString *ago = [date timeAgo];
Cell.timeLabel.text=ago;
//Cell.DefaultImg.image = [UIImage imageNamed:#"buhz_mini_logo.png"];
[Cell.DefaultImg setImageWithURL:[NSURL URLWithString:thumb_url]
placeholderImage:[UIImage imageNamed:#"buhz_mini_logo.png"]];
return Cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//Ideally you should do lazy loading so that instead of creating a new textView each time, you just reuse the same one.
UITextView *temp = [[UITextView alloc] initWithFrame:CGRectMake(82, 26, self.FeedTable.frame.size.width, 18)]; //This initial size doesn't matter
NSDictionary *tempDictionary= [self->feedArray objectAtIndex:indexPath.row];
NSString *status = [tempDictionary objectForKey:#"message"];
temp.font =[UIFont fontWithName:#"System" size:12];
temp.text = status;
CGFloat textViewWidth = 218;
CGRect tempFrame = CGRectMake(82,26,textViewWidth,18); //The height of this frame doesn't matter.
CGSize tvsize = [temp sizeThatFits:CGSizeMake(tempFrame.size.width, tempFrame.size.height)]; //This calculates the necessary size so that all the text fits in the necessary width.
//Add the height of the other UI elements inside your cell
return tvsize.height + 70;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"commentSegue"]) {
}
}
#end
publicfeed .h
#import <UIKit/UIKit.h>
#interface PublicFeedViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
#property (weak, nonatomic) IBOutlet UITableView *FeedTable;
#property (weak, nonatomic) IBOutlet UIBarButtonItem *sidebarButton;
- (IBAction)addItem;
#end
So assuming that you're creating this button in code, this is how you could handle this.
This first line tells the button that when it's pressed, it needs to call this specific selector/method sent as the action.
[button addTarget:self action:#selector(showNextViewController) forControlEvents:UIControlEventTouchUpInside];
Then you would create this method in the same class.
- (void) showNextViewController
{
NewViewController *newViewController = [[NewViewController alloc] init]; //Edit this line of course to fit for your situation. I'm not sure if you're loading from an XIB or from a Storyboard, or neither.
newViewController.someVariable = someVariable;
newViewController.someOtherVariable = someOtherVariable;
[[[[[UIApplication sharedApplication] delegate] window] rootViewController].navigationController pushViewController:view animated:YES];
}
This will send the necessary data to the new view controller, and it will also display the new view on the screen with a back button.
Hope this works!
1. Ok so lets pretend this is your custom cell class.
in your .h file of the custom cell you need to add a protocol.
#import <UIKit/UIKit.h>
#interface CustomCell : UIView
#property (strong, nonatomic) id delegate; //this is used for sending messages out of the custom cell
//init
- (id)initWithFrame:(CGRect)frame andCatName:(NSString *)name andDelegate:(id)delegate;
#end
#protocol CustomCellProtocol <NSObject>
-(void)customCellSelected:(NSString *)cellName;
#end
what we actually did is something like creating a custom event that the class can throw out and everyone who subscribes to that can run a method when customCellSelected is thrown.
2. now when you create each custom cell with the init method you need to provide a delegate which kind of points to which class should the custom cell transfer the call to customCellSelected so in the init method you set that delegate.
- (id)initWithFrame:(CGRect)frame andDelegate:(id)delegate {
self = [super initWithFrame:frame];
if (self) {
self.delegate = delegate; //setting which class should be called when calling protocol methods.
// Your initialization code
}
return self;
}
3. now in your .m file of the custom cell, when the user presses your button and you enter your method , let it be buttonPressed
- (IBAction) buttonPressed:(id)sender {
[self.delegate customCellSelected:#"THE CELL'S NAME"]; // calling the protocol method.
}
now the call to the delegate method should be transferred to the vc because when you create the custom cell you use initWithFrame:(CGRect)frame andDelegate:(id)delegate and you transfer self as the delegate , so when [self.delegate customCellSelected:#"THE CELL'S NAME"]; is called it is actually called on the vc.
4. this is how you create the custom cell in the vc:
customCell *tempView = [[customCell alloc] initWithFrame:CGRectMake(X, Y, Width, Height) andDelegate:self]; // here you set the vc as the delegate
5.and now all you have to do is add the method customCellSelected to your vc code so it can called when the customCell is calling it.
- (void)customCellSelected:(NSString *)cellName {
self.selectedCell = cellName;
[self performSegueWithIdentifier:#"SelectedCell" sender:self];
}
6.then add this in the vc:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"SelectedCell"]) {
LevelSelectViewController *levelSelectViewController = (LevelSelectViewController *)segue.destinationViewController;
levelSelectViewController.cellName = self.selectedCell;
}
}
7.only thing you have to remember is to create a segue from your first vc to the second like this:

Set label for a custom cell

I have a custom table cell and I'm just trying to set the label, image, etc but for some reason it's not working.
Here is my code for my custom cell
BrowserMenuCell.h
#import <UIKit/UIKit.h>
#interface BrowseMenuCell : UITableViewCell
#property (strong, nonatomic) IBOutlet UIButton *wishListBUtton;
#property (strong, nonatomic) IBOutlet UIImageView *itemImage;
#property (strong, nonatomic) IBOutlet UILabel *itemLabel;
#property (strong, nonatomic) IBOutlet UILabel *itemPrice;
#property (strong, nonatomic) IBOutlet UITextField *quantityField;
#property (strong, nonatomic) IBOutlet UILabel *totalLabel;
- (IBAction)plusButton:(id)sender;
- (IBAction)cartButton:(id)sender;
- (IBAction)minusButton:(id)sender;
#end
BrowserMenuCell.m
#import "BrowseMenuCell.h"
#implementation BrowseMenuCell
- (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
}
- (IBAction)plusButton:(id)sender {
}
- (IBAction)cartButton:(id)sender {
}
- (IBAction)minusButton:(id)sender {
}
#end
Cell for row at index path
-(UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
BrowseMenuCell *cell = [tableView dequeueReusableCellWithIdentifier:#"ItemsCell"];
OfficeSupply *supply = [_items objectAtIndex:indexPath.row];
if(cell == nil)
{
NSArray * views = [[NSBundle mainBundle] loadNibNamed:#"BrowseMenuCell" owner:nil options:nil];
for (id obj in views){
if([obj isKindOfClass:[UITableViewCell class]])
{
BrowseMenuCell * obj = [[BrowseMenuCell alloc]init];
obj.itemLabel.text = supply.itemName;
cell = obj;
break;
}
}
}
return cell;
}
Have you tried using [self.tableView reloadData]?
To start with, don't create a new random instance of the cell after you have already created one from the NIB file. Change the code to this:
for (BrowseMenuCell *obj in views){
if([obj isKindOfClass:[BrowseMenuCell class]])
{
obj.reuseIdentifier = #"ItemsCell";
obj.itemLabel.text = supply.itemName;
cell = obj;
break;
}
}
That won't guarantee it works, but at least the NIB setup of your labels won't be getting thrown away.
If it still doesn't work. Debug. Check the frames of the labels. Check the label references are set (not nil).
This is the wrong way you create cell. Try this one:
-(UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
BrowseMenuCell *cell = (BrowseMenuCell*)[tableView dequeueReusableCellWithIdentifier:#"ItemsCell"];
OfficeSupply *supply = [_items objectAtIndex:indexPath.row];
if (_cellObj == nil) {
[[NSBundle mainBundle] loadNibNamed:#"BrowseMenuCell" owner:nil options:nil];
}
cell.itemlabel.text = supply.itemName;
return cell;
}

Resources