I currently have a UITableView within my MatchCenterViewController, and I designed it to load up 10 rows for every section, but only show the first 4 by making the heightForRowAtIndexPath return a value of 0 for the rest. What I want to do is have a button on the bottom of every section that when pressed, will reload the data and show 10 instead of 4 for just that specific section.
I've started working on the framework for what happens when the button is pressed, I'm just having trouble with the syntax for rendering the button on the bottom and showing 10 rows for only that respective section. Here's how I have my UITableView laid out so far:
MatchCenterViewController.h:
#import <UIKit/UIKit.h>
#import <Parse/Parse.h>
#import "AsyncImageView.h"
#import "SearchViewController.h"
#import "WebViewController.h"
#import "SLExpandableTableView.h"
#interface MatchCenterViewController : UIViewController <UITableViewDataSource>
#property (strong, nonatomic) NSString *itemSearch;
#property (nonatomic, strong) NSArray *imageURLs;
#property (strong, nonatomic) NSString *matchingCategoryCondition;
#property (strong, nonatomic) NSString *matchingCategoryLocation;
#property (strong, nonatomic) NSNumber *matchingCategoryMaxPrice;
#property (strong, nonatomic) NSNumber *matchingCategoryMinPrice;
#property (strong, nonatomic) NSArray *matchCenterArray;
#property (strong, nonatomic) NSString *searchTerm;
#property (strong, nonatomic) NSString *itemURL;
#end
MatchCenterViewController.m:
#import "MatchCenterViewController.h"
#import <UIKit/UIKit.h>
#interface MatchCenterViewController () <UITableViewDataSource, UITableViewDelegate>
#property (nonatomic, strong) UITableView *matchCenter;
#property (nonatomic, assign) BOOL matchCenterDone;
#property (nonatomic, assign) BOOL hasPressedShowMoreButton;
#end
#implementation MatchCenterViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_matchCenterDone = NO;
//self.matchCenter = [[SLExpandableTableView alloc] initWithFrame:self.view.bounds style:UITableViewCellStyleSubtitle];
self.matchCenter = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewCellStyleSubtitle];
self.matchCenter.frame = CGRectMake(0,50,320,self.view.frame.size.height-100);
_matchCenter.dataSource = self;
_matchCenter.delegate = self;
[self.view addSubview:self.matchCenter];
_matchCenterArray = [[NSArray alloc] init];
}
- (void)viewDidAppear:(BOOL)animated
{
self.matchCenterArray = [[NSArray alloc] init];
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
activityIndicator.center = CGPointMake(self.view.frame.size.width / 2.0, self.view.frame.size.height / 2.0);
[self.view addSubview: activityIndicator];
[activityIndicator startAnimating];
_matchCenterDone = NO;
// Disable ability to scroll until table is MatchCenter table is done loading
self.matchCenter.scrollEnabled = NO;
[PFCloud callFunctionInBackground:#"MatchCenter2"
withParameters:#{}
block:^(NSArray *result, NSError *error) {
if (!error) {
_matchCenterArray = result;
[activityIndicator stopAnimating];
[_matchCenter reloadData];
_matchCenterDone = YES;
self.matchCenter.scrollEnabled = YES;
NSLog(#"Result: '%#'", result);
}
}];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return _matchCenterArray.count;
}
//the part where i setup sections and the deleting of said sections
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 21.0f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
return 0.01f;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 21)];
headerView.backgroundColor = [UIColor lightGrayColor];
_searchTerm = [[[[_matchCenterArray objectAtIndex:section] objectForKey:#"Top 3"] objectAtIndex:0]objectForKey:#"Search Term"];
UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(8, 0, 250, 21)];
headerLabel.text = [NSString stringWithFormat:#"%#", _searchTerm];
headerLabel.font = [UIFont boldSystemFontOfSize:[UIFont systemFontSize]];
headerLabel.textColor = [UIColor whiteColor];
headerLabel.backgroundColor = [UIColor lightGrayColor];
[headerView addSubview:headerLabel];
UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
deleteButton.tag = section;
deleteButton.frame = CGRectMake(300, 2, 17, 17);
[deleteButton setImage:[UIImage imageNamed:#"xbutton.png"] forState:UIControlStateNormal];
[deleteButton addTarget:self action:#selector(deleteButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[headerView addSubview:deleteButton];
return headerView;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSDictionary *currentSectionDictionary = _matchCenterArray[section];
NSArray *top3ArrayForSection = currentSectionDictionary[#"Top 3"];
return top3ArrayForSection.count-1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Initialize cell
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
// if no cell could be dequeued create a new one
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// No cell separators = clean design
tableView.separatorColor = [UIColor clearColor];
// title of the item
cell.textLabel.text = _matchCenterArray[indexPath.section][#"Top 3"][indexPath.row+1][#"Title"];
cell.textLabel.font = [UIFont boldSystemFontOfSize:14];
// price of the item
cell.detailTextLabel.text = [NSString stringWithFormat:#"$%#", _matchCenterArray[indexPath.section][#"Top 3"][indexPath.row+1][#"Price"]];
cell.detailTextLabel.textColor = [UIColor colorWithRed:0/255.0f green:127/255.0f blue:31/255.0f alpha:1.0f];
// image of the item
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:_matchCenterArray[indexPath.section][#"Top 3"][indexPath.row+1][#"Image URL"]]];
[[cell imageView] setImage:[UIImage imageWithData:imageData]];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row > 3 || self.hasPressedShowMoreButton){
return 0;
}
else{
return 65;
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (_matchCenterDone == YES) {
self.itemURL = _matchCenterArray[indexPath.section][#"Top 3"][indexPath.row][#"Item URL"];
[self performSegueWithIdentifier:#"WebViewSegue" sender:self];
}
}
-(IBAction)pressedShowMoreButton{
self.hasPressedShowMoreButton = YES;
[self.matchCenter reloadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
WebViewController *controller = (WebViewController *) segue.destinationViewController;
controller.itemURL = self.itemURL;
}
#end
for this functionality you can either use special UITableviewCell or a footerView of UITableView
You can use property tableFooterView.
Below is how I use in showing load more option
UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 65)];
v.backgroundColor = [UIColor clearColor];
int mySiz = 0;
// keep counter how many times load more is pressed.. initial is 0 (this is like index)
mySiz = [startNumberLabel.text intValue]+1;
// i have 15 bcz my index size is 15.
if ([feeds count]>=(15*mySiz)) {
NSLog(#"showing button...");
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(10, 10, 296, 45)];
[button setBackgroundImage:[UIImage imageNamed:localize(#"loadmore")] forState:UIControlStateNormal];
[button addTarget:self action:#selector(loadMoreData:) forControlEvents:UIControlEventTouchUpInside];
[v addSubview:button];
mainTableView.tableFooterView = v;
} else {
mainTableView.tableFooterView = nil;
}
[mainTableView reloadData];
Now adjust code as per your necessity...
Ended up doing it like this:
// Create "more" button
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
view.backgroundColor = [UIColor whiteColor];
self.moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
self.moreButton.frame = CGRectMake(0, 0, 320, 44);
[self.moreButton setImage:[UIImage imageNamed:#"downarrow.png"] forState:UIControlStateNormal];
[self.moreButton addTarget:self action:#selector(moreButtonSelected:) forControlEvents:UIControlEventTouchUpInside];
[view addSubview:self.moreButton];
return view;
}
// Load rest of items
- (void)moreButtonSelected:(id)sender {
if (_hasPressedShowMoreButton == NO){
self.hasPressedShowMoreButton = YES;
}
else if (_hasPressedShowMoreButton == YES){
self.hasPressedShowMoreButton = NO;
}
[self.matchCenter reloadData];
}
Related
i am doing feedback form using UITableview in that using custom checkbox for selection.In a UITableviewcell i placed four static buttons for options like,Very
Good,Good,Average,Below Average.
What i want is,i want to select only one button checked in a row, if i select another button checked automatically previous selected button should be unchecked.
Example: In same row suppose if i select Very Good first again i selected Average , previous selected Very Good should be unchecked.
Check My code Below for reference:
This is in cellforrowatindexpath
[cell.R1_BTN setImage:[UIImage imageNamed:#"Touch_G.png"] forState:UIControlStateNormal];
[cell.R1_BTN addTarget:self action:#selector(BtnClicked:) forControlEvents:UIControlEventTouchUpInside];
cell.R1_BTN.tag=1;
Click event here..
-(void)BtnClicked:(id)sender
{
//Need Code Here..
}
updated code for reference..
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [GNM count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [GNM objectAtIndex:section];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([[NM objectAtIndex:section] isKindOfClass:[NSArray class]])
{
return [[NM objectAtIndex:section] count];
}
else
{
return 1;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
FeedBackFormTVC *cell = [FeedBack_TV dequeueReusableCellWithIdentifier:#"ListCell" forIndexPath:indexPath];
cell.FBName_LBL.text = [[NM objectAtIndex:indexPath.section] isKindOfClass:[NSArray class]]
? [[NM objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]
: [NM objectAtIndex:indexPath.section];
// below for assigning code action event..
....
....
...
}
I tried using Tags,but i didn't get what i want, pls help me.. thanks in Advance.
I think that you should use model to set for UITableViewCell. Your model's .h file like :
#import <Foundation/Foundation.h>
typedef enum : NSInteger {
UNKNOWN = 0,
VERY_GOOD = 1,
GOOD = 2,
AVERAGE = 3,
BELOW_AVERAGE = 4
}RangeMark;
#interface CellModel : NSObject
#property(nonatomic, assign) RangeMark range;
#end
.m file like:
#import "CellModel.h"
#implementation CellModel
#end
than you should init a table cell with .xib file looks like:
and its .h file like :
#import <UIKit/UIKit.h>
#import "CellModel.h"
#interface TableViewCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UIButton *veryGoodButton;
#property (weak, nonatomic) IBOutlet UIButton *goodButton;
#property (weak, nonatomic) IBOutlet UIButton *averageButton;
#property (weak, nonatomic) IBOutlet UIButton *belowAverageButton;
- (void)setupCellWithModel:(CellModel*)model;
#end
its .m file like :
#import "TableViewCell.h"
#implementation TableViewCell
- (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
}
- (void)setupCellWithModel:(CellModel *)model {
if(model.range == VERY_GOOD) {
self.veryGoodButton.backgroundColor = [UIColor greenColor];
}
else if(model.range == GOOD) {
self.goodButton.backgroundColor = [UIColor blueColor];
}
else if(model.range == AVERAGE) {
self.averageButton.backgroundColor = [UIColor yellowColor];
}
else if(model.range == BELOW_AVERAGE) {
self.belowAverageButton.backgroundColor = [UIColor redColor];
}
}
- (void)prepareForReuse {
[super prepareForReuse];
self.veryGoodButton.backgroundColor = [UIColor lightGrayColor];
self.goodButton.backgroundColor = [UIColor lightGrayColor];
self.averageButton.backgroundColor = [UIColor lightGrayColor];
self.belowAverageButton.backgroundColor = [UIColor lightGrayColor];
}
#end
Finally your view controller .h file should look like :
#import <UIKit/UIKit.h>
#import "TableViewCell.h"
#interface ViewController : UIViewController
#property (weak, nonatomic) IBOutlet UITableView *tableView;
#end
and .m file should look like :
#import "ViewController.h"
#interface ViewController () <UITableViewDelegate, UITableViewDataSource>{
NSMutableArray<CellModel*> *modelList;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.estimatedRowHeight = 600;
self.tableView.rowHeight = UITableViewAutomaticDimension;
modelList = [NSMutableArray<CellModel*> new];
for (int i=0; i<50; i++) {
CellModel *cellModel = [[CellModel alloc] init];
cellModel.range = UNKNOWN;
[modelList addObject:cellModel];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
TableViewCell *cell = (TableViewCell*)[tableView dequeueReusableCellWithIdentifier:#"TableViewCell"];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"TableViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
[cell setupCellWithModel:[modelList objectAtIndex:indexPath.row]];
cell.veryGoodButton.tag = indexPath.row;
cell.goodButton.tag = indexPath.row;
cell.averageButton.tag = indexPath.row;
cell.belowAverageButton.tag = indexPath.row;
[cell.veryGoodButton addTarget:self action:#selector(veryGood:) forControlEvents:UIControlEventTouchUpInside];
[cell.goodButton addTarget:self action:#selector(good:) forControlEvents:UIControlEventTouchUpInside];
[cell.averageButton addTarget:self action:#selector(average:) forControlEvents:UIControlEventTouchUpInside];
[cell.belowAverageButton addTarget:self action:#selector(belowAverage:) forControlEvents:UIControlEventTouchUpInside];
return cell;
return nil;
}
- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return modelList.count;
}
- (void) veryGood:(UIButton*)sender {
[modelList objectAtIndex: sender.tag].range = VERY_GOOD;
[self setCellDynamicly:[NSIndexPath indexPathForRow:sender.tag inSection:0] withCellModel:[modelList objectAtIndex: sender.tag]];
}
- (void) good:(UIButton*)sender {
[modelList objectAtIndex: sender.tag].range = GOOD;
[self setCellDynamicly:[NSIndexPath indexPathForRow:sender.tag inSection:0] withCellModel:[modelList objectAtIndex: sender.tag]];
}
- (void) average:(UIButton*)sender {
[modelList objectAtIndex: sender.tag].range = AVERAGE;
[self setCellDynamicly:[NSIndexPath indexPathForRow:sender.tag inSection:0] withCellModel:[modelList objectAtIndex: sender.tag]];
}
- (void) belowAverage:(UIButton*)sender {
[modelList objectAtIndex: sender.tag].range = BELOW_AVERAGE;
[self setCellDynamicly:[NSIndexPath indexPathForRow:sender.tag inSection:0] withCellModel:[modelList objectAtIndex: sender.tag]];
}
- (void)setCellDynamicly:(NSIndexPath*)indexPath withCellModel:(CellModel*)cellModel {
TableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
[cell prepareForReuse];
[cell setupCellWithModel:cellModel];
}
#end
that s all :)
At the end app looks like :
yes this will be a solution for you, at least I hope like this :)
first of all create a custom button .h file like this :
#import <UIKit/UIKit.h>
#interface CustomButton : UIButton
#property (assign) NSInteger sectionTag;
#property (assign) NSInteger rowTag;
#end
custom button .m file like this :
#import "CustomButton.h"
#implementation CustomButton
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
#end
then I changed a few things in TableViewCell .h file like this :
#import <UIKit/UIKit.h>
#import "CellModel.h"
#import "CustomButton.h"
#interface TableViewCell : UITableViewCell
#property (weak, nonatomic) IBOutlet CustomButton *veryGoodButton;
#property (weak, nonatomic) IBOutlet CustomButton *goodButton;
#property (weak, nonatomic) IBOutlet CustomButton *averageButton;
#property (weak, nonatomic) IBOutlet CustomButton *belowAverageButton;
#property (weak, nonatomic) IBOutlet UILabel *itemLabel;
- (void)setupCellWithModel:(CellModel*)model;
#end
TableViewCell .m file like this :
#import "TableViewCell.h"
#implementation TableViewCell
- (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
}
- (void)setupCellWithModel:(CellModel *)model {
if(model.range == VERY_GOOD) {
self.veryGoodButton.backgroundColor = [UIColor greenColor];
}
else if(model.range == GOOD) {
self.goodButton.backgroundColor = [UIColor blueColor];
}
else if(model.range == AVERAGE) {
self.averageButton.backgroundColor = [UIColor yellowColor];
}
else if(model.range == BELOW_AVERAGE) {
self.belowAverageButton.backgroundColor = [UIColor redColor];
}
[self.itemLabel setText:model.itemText];
}
- (void)prepareForReuse {
[super prepareForReuse];
self.veryGoodButton.backgroundColor = [UIColor lightGrayColor];
self.goodButton.backgroundColor = [UIColor lightGrayColor];
self.averageButton.backgroundColor = [UIColor lightGrayColor];
self.belowAverageButton.backgroundColor = [UIColor lightGrayColor];
}
and its .xib like this :
on the other side, there is only one change on CellModel .h file like this :
#import <Foundation/Foundation.h>
typedef enum : NSInteger {
UNKNOWN = 0,
VERY_GOOD = 1,
GOOD = 2,
AVERAGE = 3,
BELOW_AVERAGE = 4
}RangeMark;
#interface CellModel : NSObject
#property(nonatomic, assign) RangeMark range;
#property(nonatomic, copy) NSString* itemText;
- (id)initWith:(NSString*)itemText withRangeMark:(RangeMark)range;
#end
and its .m file like this :
#import "CellModel.h"
#implementation CellModel
- (id)initWith:(NSString*)itemText withRangeMark:(RangeMark)range {
self = [super init];
if(self) {
self.itemText = itemText;
self.range = range;
}
return self;
}
#end
finally view controller .h file same but .m like this :
#import "ViewController.h"
#interface ViewController () <UITableViewDelegate, UITableViewDataSource>{
NSMutableArray *modelList;
NSMutableArray<NSString*> *sectionTitleList;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.estimatedRowHeight = 600;
self.tableView.rowHeight = UITableViewAutomaticDimension;
sectionTitleList = [NSMutableArray<NSString*> new];
[sectionTitleList addObject:#"RESERVATION"];
[sectionTitleList addObject:#"FRONT DESK"];
[sectionTitleList addObject:#"CASHIER"];
[sectionTitleList addObject:#"HOUSE KEEPING"];
modelList = [[NSMutableArray alloc] initWithCapacity: 4];
[modelList insertObject:[NSMutableArray arrayWithObjects:[[CellModel alloc] initWith:#"Service Speed" withRangeMark:UNKNOWN],[[CellModel alloc] initWith:#"Good Speed" withRangeMark:UNKNOWN],[[CellModel alloc] initWith:#"Confirmation Quality" withRangeMark:UNKNOWN],[[CellModel alloc] initWith:#"Quick Service in Reservetion" withRangeMark:UNKNOWN],nil] atIndex:0];
[modelList insertObject:[NSMutableArray arrayWithObjects:[[CellModel alloc] initWith:#"Check In" withRangeMark:UNKNOWN],[[CellModel alloc] initWith:#"Happy on Their Service" withRangeMark:UNKNOWN],[[CellModel alloc] initWith:#"Coutesey" withRangeMark:UNKNOWN],[[CellModel alloc] initWith:#"Quick Service at Check In" withRangeMark:UNKNOWN],nil] atIndex:1];
[modelList insertObject:[NSMutableArray arrayWithObjects:[[CellModel alloc] initWith:#"Front Office & Reception" withRangeMark:UNKNOWN],[[CellModel alloc] initWith:#"Overall Quality of Room" withRangeMark:UNKNOWN],[[CellModel alloc] initWith:#"Check" withRangeMark:UNKNOWN],[[CellModel alloc] initWith:#"Response Time" withRangeMark:UNKNOWN],nil] atIndex:2];
[modelList insertObject:[NSMutableArray arrayWithObjects:[[CellModel alloc] initWith:#"Room Decor" withRangeMark:UNKNOWN],nil] atIndex:3];
// [modelList addObject: [[CellModel alloc] initWith:#"Service Speed" withRangeMark:UNKNOWN]];
// [modelList addObject: [[CellModel alloc] initWith:#"Good Speed" withRangeMark:UNKNOWN]];
// [modelList addObject: [[CellModel alloc] initWith:#"Confirmation Quality" withRangeMark:UNKNOWN]];
// [modelList addObject: [[CellModel alloc] initWith:#"Quick Service in Reservetion" withRangeMark:UNKNOWN]];
// for (int i=0; i<5; i++) {
// CellModel *cellModel = [[CellModel alloc] init];
// cellModel.range = UNKNOWN;
// cellModel.itemText = #"";
// [modelList addObject:cellModel];
// }
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
TableViewCell *cell = (TableViewCell*)[tableView dequeueReusableCellWithIdentifier:#"TableViewCell"];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"TableViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
NSLog(#"section: %ld - row : %ld - item text : %#", (long)indexPath.section, (long)indexPath.row, ((CellModel*)[[modelList objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]).itemText);
[cell setupCellWithModel:[[modelList objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]];
((CustomButton*)cell.veryGoodButton).rowTag = indexPath.row;
((CustomButton*)cell.veryGoodButton).sectionTag = indexPath.section;
((CustomButton*)cell.goodButton).rowTag = indexPath.row;
((CustomButton*)cell.goodButton).sectionTag = indexPath.section;
((CustomButton*)cell.averageButton).rowTag = indexPath.row;
((CustomButton*)cell.averageButton).sectionTag = indexPath.section;
((CustomButton*)cell.belowAverageButton).rowTag = indexPath.row;
((CustomButton*)cell.belowAverageButton).sectionTag = indexPath.section;
[cell.veryGoodButton addTarget:self action:#selector(veryGood:) forControlEvents:UIControlEventTouchUpInside];
[cell.goodButton addTarget:self action:#selector(good:) forControlEvents:UIControlEventTouchUpInside];
[cell.averageButton addTarget:self action:#selector(average:) forControlEvents:UIControlEventTouchUpInside];
[cell.belowAverageButton addTarget:self action:#selector(belowAverage:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}
- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [[modelList objectAtIndex:section] count];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return sectionTitleList.count;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 18)];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, tableView.frame.size.width, 18)];
[label setFont:[UIFont boldSystemFontOfSize:12]];
[label setTextColor:[UIColor whiteColor]];
NSString *string =[sectionTitleList objectAtIndex:section];
[label setText:string];
[view addSubview:label];
[view setBackgroundColor:[UIColor darkGrayColor]];
return view;
}
- (void) veryGood:(CustomButton*)sender {
((CellModel*)[[modelList objectAtIndex:sender.sectionTag] objectAtIndex:sender.rowTag]).range = VERY_GOOD;
[self setCellDynamicly:[NSIndexPath indexPathForRow:sender.rowTag inSection:sender.sectionTag] withCellModel:[[modelList objectAtIndex:sender.sectionTag] objectAtIndex:sender.rowTag]];
}
- (void) good:(CustomButton*)sender {
((CellModel*)[[modelList objectAtIndex:sender.sectionTag] objectAtIndex:sender.rowTag]).range = GOOD;
[self setCellDynamicly:[NSIndexPath indexPathForRow:sender.rowTag inSection:sender.sectionTag] withCellModel:[[modelList objectAtIndex:sender.sectionTag] objectAtIndex:sender.rowTag]];
}
- (void) average:(CustomButton*)sender {
((CellModel*)[[modelList objectAtIndex:sender.sectionTag] objectAtIndex:sender.rowTag]).range = AVERAGE;
[self setCellDynamicly:[NSIndexPath indexPathForRow:sender.rowTag inSection:sender.sectionTag] withCellModel:[[modelList objectAtIndex:sender.sectionTag] objectAtIndex:sender.rowTag]];
}
- (void) belowAverage:(CustomButton*)sender {
((CellModel*)[[modelList objectAtIndex:sender.sectionTag] objectAtIndex:sender.rowTag]).range = BELOW_AVERAGE;
[self setCellDynamicly:[NSIndexPath indexPathForRow:sender.rowTag inSection:sender.sectionTag] withCellModel:[[modelList objectAtIndex:sender.sectionTag] objectAtIndex:sender.rowTag]];
}
- (void)setCellDynamicly:(NSIndexPath*)indexPath withCellModel:(CellModel*)cellModel {
TableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
[cell prepareForReuse];
[cell setupCellWithModel:cellModel];
}
#end
I think that it will work fine for you. Just do some change part of array init on code to dynamic :)
last appearance :
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.estimatedRowHeight = 600;
self.tableView.rowHeight = UITableViewAutomaticDimension;
sectionTitleList = [NSMutableArray<NSString*> new];
for (NSString* sectionTitle in yourSectionResponseArray) {
[sectionTitleList addObject: sectionTitle];
}
modelList = [[NSMutableArray alloc] initWithCapacity: [sectionTitleList count]];
//your row title array has to be 2D array.
for(int i = 0; i < [sectionTitleList count]; i++) {
NSMutableArray* rowStringArray = [NSMutableArray new];
for(NSString* rowTitle in [your2DRowResponseArray objectAtIndex:i]) {
[rowStringArray addObject: rowTitle];
}
[modelList insertObject: rowStringArray];
}
}
May be this can help you.
Since you haven't provided us the API response details as requested earlier we are forced to use static value. Please replace sectionTitleList & modelList from the array API response. Please find the below code to be used to assign you API response to model created by #Gökhan Aydın .
sectionTitleList = #[#"RESERVATION",#"FRONT DESK",#"CASHIER",#"HOUSE KEEPING",#"COMMON"];
modelList = #[
#[
#"Service Speed",
#"Good Service",
#"Confirmation quality",
#"Quick Service in Reservation"
],
#[
#"Check In",
#"Happy on their Service",
#"Courtesey",
#"Quick Service at Checkin"
],
#[
#"Front office & reception",
#"Overall Quality of Room",
#"Check",
#"Response time"
],
#[
#"Room Decor",
#"Time taken to serveTime taken to serveTime taken t",
#"Bathroom",
#"Facilities in the Room",
#"Choice of menu",
#"Housekeeping",
#"Room Service"
],
#[
#"Overall Comments",
#"Will you come back again"
]
];
self.navigationItem.title = [modelList lastObject];
GNM = [sectionTitleList mutableCopy];
NM = [[NSMutableArray alloc]init];
for (NSArray *feedbacktitles in modelList) {
if ([feedbacktitles isKindOfClass:[NSArray class]]) {
__block NSMutableArray *tempArray = [NSMutableArray new];
[feedbacktitles enumerateObjectsUsingBlock:^(NSString *title, NSUInteger idx, BOOL * _Nonnull stop) {
FeedbackModel *model = [[FeedbackModel alloc]initWith:title withRangeMark:UNKNOWN];
[tempArray addObject:model];
if (idx == [feedbacktitles count] - 1 ) {
*stop = TRUE;
[self->NM addObject:tempArray];
tempArray = [NSMutableArray new];
}
}];
}
}
or by simple for loop
for (NSArray *feedbacktitles in modelList) {
NSLog(#"%#",feedbacktitles);
NSMutableArray* rowStringArray = [NSMutableArray new];
if ([feedbacktitles isKindOfClass:[NSArray class]]) {
for(int i = 0; i < [feedbacktitles count]; i++) {
NSString* rowTitle = [feedbacktitles objectAtIndex:i];
FeedbackModel *model = [[FeedbackModel alloc]initWith:rowTitle withRangeMark:UNKNOWN];
[rowStringArray addObject: model];
if (i == [feedbacktitles count] - 1) {
[NM addObject: rowStringArray];
rowStringArray = [NSMutableArray new];
}
}
}
}
I'm working on an iOS app and I created an UIViewController where I put my components and it works fine .
Now I'm trying to create a Custom UIView and to put my WebView and my SearchController into . I spent a lot of time without success .
Here is my .m file and I hope some one can help me with :
#import "HomeViewController.h"
#define widthtScreen [UIScreen mainScreen].bounds.size.width
#define heightScreen [UIScreen mainScreen].bounds.size.height
#interface HomeViewController () <UISearchResultsUpdating,UISearchBarDelegate,UIBarPositioningDelegate,UITableViewDataSource,UITableViewDelegate,MapWebViewDelegate>
#property(strong,nonatomic) MapWebView *webView;
#property (nonatomic) UIButton *btnGeolocate;
#property (nonatomic, strong) UISearchController *searchController;
#end
#implementation HomeViewController{
NSMutableArray *placesList;
BOOL isSearching;
}
-(void)loadView
{
[super loadView];
self.webView = [[MapWebView alloc] initWithFrame:CGRectMake(0, -100, widthtScreen, heightScreen+100)];
self.webView.mapWebViewDelegate = self;
[self.view addSubview:self.webView];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.navigationItem.hidesBackButton = YES;
mainDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
placesList = [[NSMutableArray alloc] init];
[self initializeSearchController];
mainDelegate.webView = self.webView;
self.btnGeolocate = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width-75,550,60,60)];
self.btnGeolocate.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
[self.btnGeolocate setBackgroundImage:[UIImage imageNamed:#"geo.png"]
forState:UIControlStateNormal];
[self.btnGeolocate addTarget:self action:#selector(btnGeolocatePressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.btnGeolocate];
mainDelegate.btnZoomIn = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width-80,620,30,30)];
mainDelegate.btnZoomIn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
[mainDelegate.btnZoomIn setBackgroundColor:[UIColor blackColor]];
[mainDelegate.btnZoomIn addTarget:self action:#selector(btnZoomInPressed:) forControlEvents:UIControlEventTouchUpInside];
mainDelegate.btnZoomIn.tag=1;
UIImage *btnImage = [UIImage imageNamed:#"plus.png"];
[mainDelegate.btnZoomIn setImage:btnImage forState:UIControlStateNormal];
[self.view addSubview:mainDelegate.btnZoomIn];
mainDelegate.btnZoomOut = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width-40,620,30,30)];
mainDelegate.btnZoomOut.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
[mainDelegate.btnZoomOut setBackgroundColor:[UIColor blackColor]];
[mainDelegate.btnZoomOut addTarget:self action:#selector(btnZoomOutPressed:) forControlEvents:UIControlEventTouchUpInside];
mainDelegate.btnZoomOut.tag=1;
UIImage *btnImage2 = [UIImage imageNamed:#"minus.png"];
[mainDelegate.btnZoomOut setImage:btnImage2 forState:UIControlStateNormal];
[self.view addSubview:mainDelegate.btnZoomOut];
}
- (BOOL)slideNavigationControllerShouldDisplayLeftMenu
{
return YES;
}
- (BOOL)slideNavigationControllerShouldDisplayRightMenu
{
return YES;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSLog(#"number :%lu",(unsigned long)[placesList count]);
return [placesList count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
SuggestResultObject *sro = [SuggestResultObject new];
sro = [placesList objectAtIndex:indexPath.row];
cell.textLabel.text = sro.textPlace;
return cell;
}
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
self.navigationItem.leftBarButtonItem = nil;
self.navigationItem.rightBarButtonItem =nil;
return true;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
self.navigationItem.leftBarButtonItem = mainDelegate.leftBarButtonItem;
self.navigationItem.rightBarButtonItem = mainDelegate.rightBarButtonItem;
SuggestResultObject *sro = [SuggestResultObject new];
sro = [placesList objectAtIndex:indexPath.row];
self.searchController.active = false;
NSString *function = [[NSString alloc] initWithFormat: #"MobileManager.getInstance().moveToLocation(\"%#\",\"%#\")", sro.latPlace,sro.lonPlace];
[_webView evaluateJavaScript:function completionHandler:nil];
}
- (void)jsRun:(NSString *) searchText {
dispatch_async(dispatch_get_main_queue(), ^{
NSString *function = [[NSString alloc] initWithFormat: #"MobileManager.getInstance().setSuggest(\"%#\")", searchText];
[_webView evaluateJavaScript:function completionHandler:nil];
});
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
isSearching = YES;
}
- (void)initializeSearchController {
UITableViewController *searchResultsController = [[UITableViewController alloc] initWithStyle:UITableViewStylePlain];
searchResultsController.tableView.dataSource = self;
searchResultsController.tableView.delegate = self;
self.searchController = [[UISearchController alloc] initWithSearchResultsController:searchResultsController];
self.definesPresentationContext = YES;
self.searchController.hidesNavigationBarDuringPresentation = false;
self.searchController.accessibilityElementsHidden= true;
self.searchController.dimsBackgroundDuringPresentation = true;
self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0);
self.navigationItem.titleView = self.searchController.searchBar;
self.searchController.searchResultsUpdater = self;
self.searchController.searchBar.delegate = self;
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
self.navigationItem.leftBarButtonItem = mainDelegate.leftBarButtonItem;
self.navigationItem.rightBarButtonItem = mainDelegate.rightBarButtonItem;
NSLog(#"Cancel clicked");
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
[placesList removeAllObjects];
}
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
[placesList removeAllObjects];
if([searchController.searchBar.text length] != 0) {
isSearching = YES;
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
[self jsRun:searchController.searchBar.text];
}
else {
isSearching = NO;
[((UITableViewController *)self.searchController.searchResultsController).tableView reloadData];
}
}
-(void) btnGeolocatePressed : (id) sender{
}
-(void) btnZoomInPressed : (id) sender{
[_webView evaluateJavaScript:#"MobileManager.getInstance().zoomIn();" completionHandler:nil];
}
-(void) btnZoomOutPressed : (id) sender{
[_webView evaluateJavaScript:#"MobileManager.getInstance().zoomOut();" completionHandler:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)searchResult:(NSArray*)dataArray{
SuggestResultObject *sro = [SuggestResultObject new];
sro.textPlace = [dataArray objectAtIndex:0];
sro.lonPlace = [dataArray objectAtIndex:1];
sro.latPlace = [dataArray objectAtIndex:2];
[placesList addObject:sro];
[((UITableViewController *)self.searchController.searchResultsController).tableView reloadData];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}
#end
Screenshots (Not sure how to scale images on stackoverflow.. OSX takes images in Retina format and they're fairly large! Sorry in advance!):
http://i.imgur.com/15qxDpc.png
http://i.imgur.com/QHduP07.png
How it works? Create a UIView and two sub-views: UITableView and
UIWebView. Constrain them properly.
Create the UISearchController with a nil SearchResultsController
as the parameter to the init method.
This lets the search controller know that the results will be
displayed in the current controller/view.
Next we setup the delegates for the UISearchController and create
the function for filtering.
Now that we have the view created, we need a UIViewController to
test it. We can either add the search bar to the tableView header OR
to the NavigationController if there is one..
Below, I have chosen to add it to the UINavigationController and I
told the UISearchController to NOT HIDE the navigation bar on
presentation.
That way, the results are displayed in the current view without hiding
the navigation bar.
You can then use the webview which is hidden and offscreen to do
whatever javascript searches you are using it for..
However, a better idea would be to use JSContext to execute
Javascript instead of a UIWebView. The advantage of the UIWebView
is that you can parse HTML and modify DOM which the JSContext
doesn't allow.
Anyway..
Here is the code I wrote for a UIView that contains a
UISearchController and a UIWebView.. and then to add it to a
UIViewController that is embedded in a UINavigationController.
//
// SearchView.h
// StackOverflow
//
// Created by Brandon T on 2016-06-26.
// Copyright © 2016 XIO. All rights reserved.
//
#import <UIKit/UIKit.h>
#class SearchView;
#protocol SearchViewDelegate <UISearchBarDelegate>
- (void)didSelectRowAtIndexPath:(SearchView *)searchView tableView:(UITableView *)tableView indexPath:(NSIndexPath *)indexPath;
#end
#interface SearchView : UIView
#property (nonatomic, weak) id<SearchViewDelegate> delegate;
- (UISearchBar *)getSearchBar;
- (UIWebView *)getWebView;
#end
//
// SearchView.m
// StackOverflow
//
// Created by Brandon T on 2016-06-26.
// Copyright © 2016 XIO. All rights reserved.
//
#import "SearchView.h"
#define kTableViewCellIdentifier #"kTableViewCellIdentifier"
#interface SearchView() <UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating>
#property (nonatomic, strong) UIWebView *webView;
#property (nonatomic, strong) UISearchController *searchController;
#property (nonatomic, strong) UITableView *tableView;
#property (nonatomic, strong) NSArray *dataSource;
#property (nonatomic, strong) NSArray *searchResults;
#end
#implementation SearchView
- (instancetype)init {
if (self = [super init]) {
[self setupData];
[self initControls];
[self themeControls];
[self registerCells];
[self doLayout];
}
return self;
}
- (UISearchBar *)getSearchBar {
return _searchController.searchBar;
}
- (UIWebView *)getWebView {
return _webView;
}
- (void)setDelegate:(id<SearchViewDelegate>)delegate {
_delegate = delegate;
_searchController.searchBar.delegate = delegate;
}
- (void)setupData {
//Begin fake data
_dataSource = #[#"Cat", #"Dog", #"Bird", #"Parrot", #"Rabbit", #"Racoon", #"Rat", #"Hamster", #"Pig", #"Cow"];
//End fake data
_searchResults = [_dataSource copy];
}
- (void)initControls {
_webView = [[UIWebView alloc] init];
_searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
_tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
}
- (void)themeControls {
[_webView setHidden:YES];
[_tableView setDelegate:self];
[_tableView setDataSource:self];
_searchController.searchResultsUpdater = self;
_searchController.dimsBackgroundDuringPresentation = false;
_searchController.definesPresentationContext = true;
_searchController.hidesNavigationBarDuringPresentation = false;
}
- (void)registerCells {
[_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:kTableViewCellIdentifier];
}
- (void)doLayout {
[self addSubview:_webView];
[self addSubview:_tableView];
NSDictionary *views = #{#"webView":_webView, #"tableView": _tableView};
NSMutableArray *constraints = [[NSMutableArray alloc] init];
[constraints addObject:[NSString stringWithFormat:#"H:|-(%d)-[webView]-(%d)-|", 0, 0]];
[constraints addObject:[NSString stringWithFormat:#"H:|-(%d)-[tableView]-(%d)-|", 0, 0]];
[constraints addObject:[NSString stringWithFormat:#"V:|-(%d)-[webView(%d)]-(%d)-[tableView]-(%d)-|", -100, 100, 0, 0]];
for (NSString *constraint in constraints) {
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:constraint options:0 metrics:nil views:views]];
}
for (UIView *view in self.subviews) {
[view setTranslatesAutoresizingMaskIntoConstraints:NO];
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _searchController.active && _searchController.searchBar.text.length > 0 ? [_searchResults count] : [_dataSource count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 50;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTableViewCellIdentifier forIndexPath:indexPath];
if (_searchController.active && _searchController.searchBar.text.length > 0) {
cell.textLabel.text = _searchResults[indexPath.row];
}
else {
cell.textLabel.text = _dataSource[indexPath.row];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (self.delegate && [self.delegate respondsToSelector:#selector(didSelectRowAtIndexPath:tableView:indexPath:)]) {
[self.delegate didSelectRowAtIndexPath:self tableView:tableView indexPath:indexPath];
}
}
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
[self filterResults:searchController.searchBar.text scope:nil];
}
- (void)filterResults:(NSString *)searchText scope:(NSString *)scope {
_searchResults = [_dataSource filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id _Nonnull evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
NSString *object = [evaluatedObject uppercaseString];
return [object rangeOfString:[searchText uppercaseString]].location != NSNotFound;
}]];
[_tableView reloadData];
}
#end
Then I tested it with the below UIViewController which is embedded in a UINavigationController..
//
// ViewController.m
// StackOverflow
//
// Created by Brandon T on 2016-06-26.
// Copyright © 2016 XIO. All rights reserved.
//
#import "ViewController.h"
#import "SearchView.h"
#interface ViewController ()<SearchViewDelegate>
#property (nonatomic, strong) SearchView *searchView;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self initControls];
[self themeControls];
[self doLayout];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)initControls {
_searchView = [[SearchView alloc] init];
}
- (void)themeControls {
self.edgesForExtendedLayout = UIRectEdgeNone;
self.navigationItem.titleView = [_searchView getSearchBar];
[_searchView setDelegate:self];
}
- (void)doLayout {
[self.view addSubview:_searchView];
NSDictionary *views = #{#"searchView":_searchView};
NSMutableArray *constraints = [[NSMutableArray alloc] init];
[constraints addObject:[NSString stringWithFormat:#"H:|-%d-[searchView]-%d-|", 0, 0]];
[constraints addObject:[NSString stringWithFormat:#"V:|-%d-[searchView]-%d-|", 0, 0]];
for (NSString *constraint in constraints) {
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:constraint options:0 metrics:nil views:views]];
}
for (UIView *view in self.view.subviews) {
[view setTranslatesAutoresizingMaskIntoConstraints:NO];
}
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
self.navigationItem.leftBarButtonItems = nil;
self.navigationItem.rightBarButtonItems = nil;
}
- (void)didSelectRowAtIndexPath:(SearchView *)searchView tableView:(UITableView *)tableView indexPath:(NSIndexPath *)indexPath {
[[searchView getWebView] stringByEvaluatingJavaScriptFromString:#"SomeJavascriptHere"];
}
#end
Hi I am very new to iOS and in my project iI have created one UITableView with images as like my below screen ok that's fine
And here when I tapped on tableView images I want show that related row images with popup block using one UIView.
But using my code image is not showing on popup UIView. Please see my below screen image is not adding on UIView popup block please help me some one.
My Code:
#import "imageTableViewController.h"
#interface imageTableViewController ()<UITableViewDataSource,UITableViewDelegate>
{
UITableView *mainTable;
NSMutableArray *imageArray;
UIButton *imageButton;
UIView *popUpView;
BOOL isFullScreen;
CGRect prevFrame;
}
#end
#implementation imageTableViewController
- (void)viewDidLoad {
[super viewDidLoad];
imageArray = [[NSMutableArray alloc] initWithObjects:#"flower.jpeg",#"Bird.jpg",#"Browser.jpeg", nil];
mainTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, 320, 480)];
mainTable.dataSource = self;
mainTable.delegate = self;
[self.view addSubview:mainTable];
popUpView = [[UIView alloc] initWithFrame:CGRectMake(30, 30, 25, 25)];
popUpView.backgroundColor = [UIColor orangeColor];
popUpView.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.001, 0.001);
[mainTable addSubview:popUpView];
UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 20, 20)];
imageView.image = [UIImage imageNamed:#"flower.jpeg"];
[popUpView addSubview:imageView];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return imageArray.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"cell";
UITableViewCell *Cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (Cell == nil)
{
Cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
imageButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, 50, 50)];
[imageButton setImage:[UIImage imageNamed:[imageArray objectAtIndex:indexPath.row]] forState:UIControlStateNormal];
[imageButton addTarget:self action:#selector(imgToFullScreen:) forControlEvents:UIControlEventTouchUpInside];
[Cell.contentView addSubview:imageButton];
return Cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 60;
}
-(void)imgToFullScreen:(UITapGestureRecognizer*)sender {
if (!isFullScreen) {
[UIView animateWithDuration:0.5 delay:0 options:0 animations:^{
popUpView.hidden = NO;
prevFrame = CGRectMake(30, 30, 25, 25);
[popUpView setFrame:CGRectMake(120, 50, 150, 150)];
}completion:^(BOOL finished){
isFullScreen = TRUE;
}];
return;
}
else{
[UIView animateWithDuration:0.5 delay:0 options:0 animations:^{
[popUpView setFrame:prevFrame];
}completion:^(BOOL finished){
isFullScreen = FALSE;
popUpView.hidden = YES;
}];
return;
}
}
Looks like it's happened because of
popUpView.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.001, 0.001);
you create view and scale it to really small, also all subview will be downscaled. And then in show animation block you change frame of popup, but you have to change scale like:
popUpView.transform = CGAffineTransformScale(CGAffineTransformIdentity, 1, 1);
Edit due comment
hmm yes that's fine and one small problem is coming #in.disee that is
when i zoom in popup block images are popup like my above screen and
when i zoom out that images are must zoom out near related
rows,understand?
Your current realisation have few problems including:
Your architecture do not allow you get index path of selected cell - it will be a problem anyway, so among other you have to make this part.
It will be too hard explain in words everything you have to chage, so i write code for you) I almost do not change your code, but it would be cool if you change it to the way i write mine, because it's more convenient to apple guides
What i do:
1) create custom class for cell
2) add ability for cell say something to tableview via delegation pattern
3) when user click on button in cell - cell tells to tableview, which button of which was was pressed
4) table view convert frame of cell's image to own coordinates and show popup
you can just replace you code with this one:
#import "imageTableViewController.h"
#class CustomCell;
#protocol CustomCellDelegate <NSObject>
- (void)didSelectImageNamed:(NSString *)name fromCell:(CustomCell *)cell;
#end
#interface CustomCell : UITableViewCell
#property (nonatomic, strong) NSString *imageName;
#property (nonatomic, strong) UIButton *imageBtn;
#property (nonatomic, weak) id <CustomCellDelegate> delegate;
#property (nonatomic, assign, readonly) CGRect imageRect;
#end
#implementation CustomCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self){
[self setup];
}
return self;
}
- (CGRect)imageRect {
return self.imageBtn.frame;
}
- (void)setup {
self.imageBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, 50, 50)];
[self.imageBtn addTarget:self action:#selector(imgToFullScreen:) forControlEvents:UIControlEventTouchUpInside];
[self.contentView addSubview:self.imageBtn];
}
- (void)prepareForReuse {
[self.imageBtn setImage:nil forState:UIControlStateNormal];
}
- (void)setImageName:(NSString *)imageName {
_imageName = imageName;
[self.imageBtn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
}
- (void)imgToFullScreen:(UIButton *)sender {//btw it's not UITapGestureRecognizer *
[self.delegate didSelectImageNamed:self.imageName fromCell:self];
}
#end
#interface imageTableViewController ()
<CustomCellDelegate>
#end
#implementation imageTableViewController {
UITableView *mainTable;
NSMutableArray *imageArray;
UIButton *imageButton;
UIView *popUpView;
BOOL isFullScreen;
CGRect prevFrame;
}
- (void)viewDidLoad {
[super viewDidLoad];
imageArray = [[NSMutableArray alloc] initWithObjects:#"flower.jpeg",#"Bird.jpg",#"Browser.jpeg", nil];
mainTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, 320, 480)];
mainTable.dataSource = self;
mainTable.delegate = self;
[self.view addSubview:mainTable];
popUpView = [[UIView alloc] initWithFrame:CGRectMake(30, 30, 25, 25)];
popUpView.backgroundColor = [UIColor orangeColor];
popUpView.hidden = YES;
[mainTable addSubview:popUpView];
UIView * imageView = [[UIView alloc] initWithFrame:CGRectMake(5, 5, 20, 20)];
imageView.backgroundColor = [UIColor colorWithRed:255./255. green:0 blue:0 alpha:1];
[popUpView addSubview:imageView];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return imageArray.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"cell";
CustomCell *Cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (Cell == nil)
{
Cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
Cell.delegate = self;
}
Cell.imageName = [imageArray objectAtIndex:indexPath.row];
return Cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 60;
}
-(void)imgToFullScreen:(NSString *)imageName fromRect:(CGRect)frame {
if (!isFullScreen) {
[popUpView setFrame:frame];
[popUpView setHidden:NO];
[UIView animateWithDuration:0.5 delay:0 options:0 animations:^{
[popUpView setFrame:CGRectMake(120, 50, 150, 150)];
}completion:^(BOOL finished){
isFullScreen = YES;
prevFrame = frame;
}];
return;
}
else{
[UIView animateWithDuration:0.5 delay:0 options:0 animations:^{
[popUpView setFrame:prevFrame];
}completion:^(BOOL finished){
isFullScreen = NO;
popUpView.hidden = YES;
}];
return;
}
}
#pragma mark - CustomCellDelegate
- (void)didSelectImageNamed:(NSString *)name fromCell:(CustomCell *)cell {
CGRect imageFrame = cell.imageRect;
CGRect imageFrameGlobalCoord = [mainTable convertRect:imageFrame fromView:cell];
[self imgToFullScreen:name fromRect:imageFrameGlobalCoord];
}
#end
When I click the UITableViewCell , It have selection effect (grey background in clicked cell),But didSelectRowAtIndexPath is not calling ,what happen?
EDIT
this is my code
tableView.h file
#interface PopCardView : MMPopupView <UITableViewDataSource, UITableViewDelegate>
#end
tableView.m file
#property (nonatomic, strong) NSMutableArray *tagsArray;
#property (nonatomic, strong) UIView *backView;
#property (nonatomic, strong) UITableView *tableView;
#property (nonatomic, assign) NSUInteger lastIndex;
#end
-(id)initWithTags:(NSMutableArray *)tags{
self = [super init];
if (self) {
self.backView = [[UIView alloc] init];
self.backView.backgroundColor = [UIColor whiteColor];
self.backView.layer.cornerRadius = 5;
self.backView.layer.masksToBounds = YES;
[self addSubview:self.backView];
[self.backView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.top.bottom.right.equalTo(self);
}];
_tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 324, 300) style:UITableViewStylePlain];
_tableView.tableFooterView =[[UIView alloc] init];
[self.backView addSubview:_tableView];
[_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.top.right.bottom.equalTo(self.backView).insets(UIEdgeInsetsMake(45,0, 45, 15));
make.size.mas_equalTo(CGSizeMake(324, 200));
}];
[_tableView registerClass:[PopCardTagViewCell class] forCellReuseIdentifier:#"cell"];
_tableView.allowsSelection = YES;
_tableView.allowsSelectionDuringEditing = YES;
[_tableView setUserInteractionEnabled:YES];
_tableView.dataSource = self;
_tableView.delegate = self;
}
return self;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[_tagsArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
PopCardData *data = (PopCardData *)obj;
data.selected = #"0";
if (idx == indexPath.row) {
data.selected = #"1";
}
}];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifer = #"cell";
PopCardTagViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:identifer];
if (!cell) {
cell = [[PopCardTagViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifer];
}
[self configureCell:cell forIndexPath:indexPath];
return cell;
}
-(void)configureCell:(PopCardTagViewCell *)cell forIndexPath:(NSIndexPath *)indexPath {
PopCardData *data = (PopCardData *)[_tagsArray objectAtIndex:indexPath.row];
//configure cell
[cell setUserInteractionEnabled:YES];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return _tagsArray.count;
}
EDIT2
this is my initialize code of PopCardView,it use swift
let pop = PopCardView(tags: self.m_model.getItmes())
pop.show()
The code you show does not set any delegate to the table view. Either this is the reason or you posted an incomplete code snippet.
self.tableView.delegate = self;
and add UITableViewDelegate to your interface like
#interface ClassName ()<UITableViewDelegate>
Make sure you don't have anything in the cell that can swallow the touch event. Things like buttons and textfields can cause this. Strip everything from your cell, test to see if it works, then add things back in slowly to find the culprit.
I was trying to create a custom section for my tableview.Tableview itself works fine, but for some reason, compiler skips,
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
delegate method, and i tried what is written on the reference , and this . I also added the tableView:heightForHeaderInSection: method as it suggests in reference page but for some reason it just doesn't read these methods. Obviously, I am doing something wrong. If someone can point my mistake out, I would appreciate. Thank you in advance.
profileViewController.h
#import <UIKit/UIKit.h>
#import "PeopleModel.h"
#import <QuartzCore/QuartzCore.h>
#interface profileViewController : UIViewController
<UITableViewDataSource,UITableViewDelegate>
#property(strong,nonatomic)NSMutableArray *People;
#property (weak, nonatomic) IBOutlet UITableView *profileTableView;
#end
profileViewController.m
#import "profileViewController.h"
#interface profileViewController ()
+ (UIImage *)scale:(UIImage *)image toSize:(CGSize)size;
#end
#implementation profileViewController
- (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 = #"ProfileView";
self.profileTableView.dataSource = self;
self.profileTableView.dataSource = self;
PeopleModel *person1 = [[PeopleModel alloc]init];
person1.Name =#"mett";
person1.Email= #"mett#gmail.com";
person1.ProfilePicture =[UIImage imageNamed:#"profileImage.jpg"];
self.People = [NSMutableArray arrayWithObjects:person1,person1, nil];
self.profileTableView.layer.cornerRadius = 8.0;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.People count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.textLabel.font = [UIFont systemFontOfSize:19.0];
cell.detailTextLabel.font = [UIFont systemFontOfSize:12];
}
PeopleModel *item =[self.People objectAtIndex:indexPath.row];
cell.textLabel.text = item.Name;
cell.detailTextLabel.text = item.Email;
cell.imageView.image = item.ProfilePicture;
cell.imageView.image =[profileViewController scale:item.ProfilePicture toSize:CGSizeMake(115, 75)];
return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 15;
}
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
NSLog(#"cartman!");
if (section == 0) {
CGRect screenRect = [[UIScreen mainScreen] applicationFrame];
UIView* headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screenRect.size.width, 44.0)];
//headerView.contentMode = UIViewContentModeScaleToFill;
// Add the label
UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(10.0, -5.0, 300.0, 90.0)];
headerLabel.backgroundColor = [UIColor clearColor];
headerLabel.opaque = NO;
headerLabel.text = #"section one";
headerLabel.textColor = [UIColor blueColor];
headerLabel.highlightedTextColor = [UIColor blackColor];
//this is what you asked
headerLabel.font = [UIFont boldSystemFontOfSize:17];
headerLabel.shadowColor = [UIColor clearColor];
headerLabel.shadowOffset = CGSizeMake(0.0, 1.0);
headerLabel.numberOfLines = 0;
headerLabel.textAlignment = NSTextAlignmentCenter;
[headerView addSubview: headerLabel];
// Return the headerView
return headerView;
}
else return nil;
}
+ (UIImage *)scale:(UIImage *)image toSize:(CGSize)size
{
UIGraphicsBeginImageContext(size);
[image drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 3;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
You have a typo in the viewDidLoad method:
self.profileTableView.dataSource = self;
self.profileTableView.dataSource = self;
One of these should be delegate.