Create Custom UIView with Custom WebView and UISearchContoller - ios

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

Related

uitableview:In a same Row selected button should checked and remaining buttons should be unchecked automaticallyy

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];
}
}
}
}

How to insert a button on the bottom of every UITableView section?

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];
}

UISearchDisplayController does not entirely cover a child view controller

I have a root view controller which composes a search bar on the top and a child table view controller on the bottom. I used composition instead of assigning the search bar to the table view's header for these reasons:
I didn't want the index to overlap with the search bar (like Contacts app).
I wanted the search bar to be sticky. That is, it doesn't move when I scroll the table view (again like the Contacts app).
My table view already had a header.
Since the search bar is in the root view controller, I instantiate my search display controller in the root view controller also. There are two problems with the search UI for which I seek advice:
The translucent gray overlay does not cover the entire child table view. It leaves the top portion of the header and the index visible.
Likewise, the search results table does not cover the entirety of the child table view. I know how to manually change the frame of this results table view, but doing so only fixes just that ... the gray translucent overlay's frame is not linked to the results table view frame. Their is no property to access the overlay.
1) Idle
2) Enter Search Bar
3) Start Typing
#import "ContactsRootViewController.h"
#import "ContactsViewController.h"
#import "UIView+position.h"
#import "User.h"
#import "UserCellView.h"
#import "UserViewController.h"
#interface ContactsRootViewController ()
#property(nonatomic, strong) UISearchBar* searchBar;
#property(nonatomic, strong) ContactsViewController* contactsViewController;
#property(nonatomic, strong) UISearchDisplayController* searchController;
#property(nonatomic, strong) NSMutableArray* matchedUsers;
#end
#implementation ContactsRootViewController
#pragma mark UIViewController
- (NSString*)title
{
return #"Contacts";
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.matchedUsers = [NSMutableArray array];
self.searchBar = [[UISearchBar alloc] init];
self.searchBar.placeholder = #"Search";
[self.searchBar sizeToFit];
[self.view addSubview:self.searchBar];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
if (self.contactsViewController == nil) {
self.contactsViewController = [[ContactsViewController alloc] init];
[self addChildViewController:self.contactsViewController];
self.contactsViewController.view.frame = CGRectMake(
0.0,
self.searchBar.bottomY,
self.view.frame.size.width,
self.view.frame.size.height - self.searchBar.bottomY
);
self.contactsViewController.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
[self.view addSubview:self.contactsViewController.view];
[self.contactsViewController didMoveToParentViewController:self];
self.searchController = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self.contactsViewController];
self.searchController.delegate = self;
self.searchController.searchResultsDataSource = self;
self.searchController.searchResultsDelegate = self;
}
}
#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.matchedUsers.count;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString* identifier = #"contactsRootViewUserCell";
UserCellView* cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[UserCellView alloc] initWithIdentifier:identifier];
}
cell.user = [self.matchedUsers objectAtIndex:indexPath.row];
return cell;
}
#pragma mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self.navigationController pushViewController:[[UserViewController alloc] initWithUser:[self.matchedUsers objectAtIndex:indexPath.row]] animated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return [UserCellView height];
}
#pragma mark UISearchDisplayControllerDelegate
- (BOOL)searchDisplayController:(UISearchDisplayController*)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self.matchedUsers removeAllObjects];
searchString = [searchString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if (searchString.length > 0) {
for (User* user in self.contactsViewController.allUsers) {
NSRange match = [user.userDisplayName rangeOfString:searchString options:NSCaseInsensitiveSearch];
if (match.location != NSNotFound) {
[self.matchedUsers addObject:user];
}
}
}
return YES;
}
- (void)searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller
{
[self.searchBar resignFirstResponder];
}
#end
I re-implemented UISearchDisplayController, calling my implementation SearchController. It does the same thing and has similar delegate callbacks, but the frame of the search results can be controlled by the programmer.
Header
#import <Foundation/Foundation.h>
#class SearchController;
#protocol SearchControllerDelegate <NSObject>
#required
- (BOOL)searchController:(SearchController*)controller shouldReloadTableForSearchString:(NSString*)searchText;
#optional
- (void)searchController:(SearchController*)controller didShowSearchResultsTableView:(UITableView*)tableView;
- (void)searchController:(SearchController *)controller didHideSearchResultsTableView:(UITableView *)tableView;
- (void)searchControllerDidBeginSearch:(SearchController*)controller;
- (void)searchControllerDidEndSearch:(SearchController*)controller;
#end
#interface SearchController : UIViewController <UISearchBarDelegate>
#property(nonatomic, weak) NSObject<SearchControllerDelegate>* delegate;
#property(nonatomic, weak) NSObject<UITableViewDataSource>* searchResultsDataSource;
#property(nonatomic, weak) NSObject<UITableViewDelegate>* searchResultsDelegate;
#property(nonatomic, strong, readonly) UITableView* searchResultsTableView;
- (id)initWithSearchBar:(UISearchBar*)searchBar;
#end
Implementation
#import "SearchController.h"
#import "UIView+position.h"
#interface SearchController ()
#property(nonatomic, strong) UISearchBar* searchBar;
#property(nonatomic, strong) UIButton* searchResultsVeil;
#property(nonatomic, strong, readwrite) UITableView* searchResultsTableView;
#property(nonatomic, assign) BOOL searchResultsTableViewHidden;
- (void)didTapSearchResultsVeil;
- (void)hideSearchResults;
#end
#implementation SearchController
#pragma mark UIViewController
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self.searchResultsTableView deselectRowAtIndexPath:[self.searchResultsTableView indexPathForSelectedRow] animated:YES];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.userInteractionEnabled = NO;
}
#pragma mark SearchController ()
- (void)hideSearchResults
{
self.searchBar.text = nil;
[self.searchResultsTableView reloadData];
self.searchResultsTableViewHidden = YES;
[self.searchBar resignFirstResponder];
}
- (void)didTapSearchResultsVeil
{
[self hideSearchResults];
}
- (void)setSearchResultsTableViewHidden:(BOOL)searchResultsTableViewHidden
{
if (self.searchResultsTableView != nil) {
if (self.searchResultsTableView.hidden && !searchResultsTableViewHidden) {
self.searchResultsTableView.hidden = searchResultsTableViewHidden;
if ([self.delegate respondsToSelector:#selector(searchController:didShowSearchResultsTableView:)]) {
[self.delegate searchController:self didShowSearchResultsTableView:self.searchResultsTableView];
}
} else if (!self.searchResultsTableView.hidden && searchResultsTableViewHidden) {
self.searchResultsTableView.hidden = searchResultsTableViewHidden;
if ([self.delegate respondsToSelector:#selector(searchController:didHideSearchResultsTableView:)]) {
[self.delegate searchController:self didHideSearchResultsTableView:self.searchResultsTableView];
}
}
}
}
- (BOOL)searchResultsTableViewHidden
{
return self.searchResultsTableView == nil || self.searchResultsTableView.hidden;
}
#pragma mark SearchController
- (id)initWithSearchBar:(UISearchBar *)searchBar
{
if (self = [super init]) {
self.searchBar = searchBar;
self.searchBar.delegate = self;
}
return self;
}
- (void)setSearchResultsDataSource:(NSObject<UITableViewDataSource> *)searchResultsDataSource
{
_searchResultsDataSource = searchResultsDataSource;
if (self.searchResultsTableView != nil) {
self.searchResultsTableView.dataSource = searchResultsDataSource;
}
}
- (void)setSearchResultsDelegate:(NSObject<UITableViewDelegate> *)searchResultsDelegate
{
_searchResultsDelegate = searchResultsDelegate;
if (self.searchResultsTableView != nil) {
self.searchResultsTableView.delegate = searchResultsDelegate;
}
}
#pragma mark UISearchBarDelegate
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
if ([self.delegate searchController:self shouldReloadTableForSearchString:searchText]) {
[self.searchResultsTableView reloadData];
self.searchResultsTableViewHidden = [self.searchResultsTableView.dataSource tableView:self.searchResultsTableView numberOfRowsInSection:0] == 0;
}
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
[searchBar setShowsCancelButton:YES animated:YES];
if (self.searchResultsVeil == nil) {
self.searchResultsVeil = [[UIButton alloc] initWithFrame:self.view.bounds];
self.searchResultsVeil.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.6];
self.searchResultsVeil.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self.searchResultsVeil addTarget:self action:#selector(didTapSearchResultsVeil) forControlEvents:UIControlEventTouchUpInside];
self.searchResultsTableView = [[UITableView alloc] initWithFrame:self.searchResultsVeil.bounds style:UITableViewStylePlain];
self.searchResultsTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
if ([self.searchResultsTableView respondsToSelector:#selector(setSeparatorInset:)]) {
self.searchResultsTableView.separatorInset = UIEdgeInsetsMake(
0.0,
self.searchResultsTableView.width,
0.0,
0.0
);
}
self.searchResultsTableViewHidden = YES;
if (self.searchResultsDataSource != nil) {
self.searchResultsTableView.dataSource = self.searchResultsDataSource;
}
if (self.searchResultsDelegate != nil) {
self.searchResultsTableView.delegate = self.searchResultsDelegate;
}
[self.view addSubview:self.searchResultsVeil];
[self.searchResultsVeil addSubview:self.searchResultsTableView];
}
self.view.userInteractionEnabled = YES;
self.searchResultsVeil.hidden = NO;
if ([self.delegate respondsToSelector:#selector(searchControllerDidBeginSearch:)]) {
[self.delegate searchControllerDidBeginSearch:self];
}
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
[searchBar setShowsCancelButton:NO animated:YES];
self.view.userInteractionEnabled = NO;
self.searchResultsVeil.hidden = YES;
if ([self.delegate respondsToSelector:#selector(searchControllerDidEndSearch:)]) {
[self.delegate searchControllerDidEndSearch:self];
}
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
[self hideSearchResults];
}
#end
Usage
self.searchController = [[SearchController alloc] initWithSearchBar:self.searchBar];
self.searchController.delegate = self;
self.searchController.searchResultsDataSource = self;
self.searchController.searchResultsDelegate = self;
[self addChildViewController:self.searchController];
self.searchController.view.frame = CGRectMake(
self.searchBar.x,
self.searchBar.bottomY,
self.searchBar.width,
self.view.height - self.searchBar.bottomY
);
[self.view addSubview:self.searchController.view];
[self.searchController didMoveToParentViewController:self];
It looks like your view controller does not define a presentation context. I had a similar problem and was able to resolve it by setting
self.definesPresentationContext = YES;
in viewDidLoad. According to the documentation this property is
A Boolean value that indicates whether this view controller's view is covered when the view controller or one of its descendants presents a view controller.

iOS 7 custom cell not displaying in table view

Please bear with me, I am just starting iOS development. I am trying to display a custom tableViewCell within a storyboard tableView. I have done the following.
I have created a new .xib with a tableViewCell in it
I have then created a custom class for this. the .h file looks like this
#import <UIKit/UIKit.h>
#interface CustomTableCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UIImageView *thumbnailImageView;
#property (weak, nonatomic) IBOutlet UILabel› *titleLabel;
#end
Then in my TableViewController.m I have imported the CustomTableCell.h and I am doing following for 10 rows
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CustomTableCell";
CustomTableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"CustomTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.titleLabel.text ="test text";
return cell;
}
This seems fine to build, but when the project loads nothing happens. Any advice will be great.
I have placed a breakpoint in the cellForRowAtIndexPath method, however it never reaches this point. here is a screen shot of the simulator
You must register your .xib file. In your viewDidLoad method, add the following:
[self.tableView registerNib:[UINib nibWithNibName:#"CustomTableCell" bundle:nil]
forCellReuseIdentifier:#"CustomTableCell"];
The way you are loading the nib is really old-fashioned and outdated. It is much better (since iOS 6) to register the nib and use dequeueReusableCellWithIdentifier:forIndexPath:.
See my explanation of all four ways of getting a custom cell.
Ensure that the delegate and datasource are set in the storyboard for the UITableView. This will ensure that cellForRowAtIndexPath is getting called for each row. You can put an NSLog message in that method to verify the same thing.
Also, since you are using a storyboard, you may want to look into Prototype Cells for the UITableView. They are a much easier way of doing the same thing - creating a UITableView with custom cells.
Here's a decent tutorial on using Prototype cells within your storyboard's UITableView:
http://www.raywenderlich.com/5138/beginning-storyboards-in-ios-5-part-1
- (void) viewDidLoad {
[super viewDidLoad];
UINib *cellNib = [UINib nibWithNibName:#"CustomTableCell" bundle:[NSBundle mainBundle]];
[self.tableView registerNib:cellNib forCellReuseIdentifier:#"CustomTableCell"];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CustomTableCell";
CustomTableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell = [[CustomTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.titleLabel.text ="test text";
return cell;
}
A very basic question, but have you implemented the tableview delegate method that indicates how many cells should be displayed? The delegate method is the following:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//Return number of cells to display here
return 1;
}
Be sure to have only one item in your xib (Uitableviewcell instance)
#import <UIKit/UIKit.h>
#import "DetailViewController.h"
#import "NewViewController.h"
#import "CustomCellVC.h"
#interface FirstVC : UIViewController
{
DetailViewController *detailViewController;
NewViewController *objNewViewController;
CustomCellVC *objCustom;
NSMutableData *webData;
NSArray *resultArray;
//IBOutlet UIButton *objButton;
}
#property(strong,nonatomic)IBOutlet DetailViewController *detailViewController;
#property(strong,nonatomic)IBOutlet UITableView *objTable;
-(void)loginWS;
-(IBAction)NewFeatureButtonClk:(id)sender;
#end
#import "FirstVC.h"
#interface FirstVC ()
#end
#implementation FirstVC
#synthesize objTable;
#synthesize detailViewController;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
objTable.frame = CGRectMake(0, 20, 320, 548);
[self loginWS];
}
-(void)loginWS
{
//Para username password
NSURL *url = [NSURL URLWithString:#"http://192.168.0.100/FeatureRequestComponent/FeatureRequestComponentAPI"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req setHTTPMethod:#"POST"];
[req addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// [req addValue:[NSString stringWithFormat:#"%i",postBody.length] forHTTPHeaderField:#"Content-Length"];
[req setTimeoutInterval:60.0 ];
//[req setHTTPBody:postBody];
//[cell setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:#"CellBg.png"]]];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:req delegate:self];
if (connection)
{
webData = [[NSMutableData alloc]init];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
resultArray = [[NSArray alloc]initWithArray:[responseDict valueForKey:#"city"]];
NSLog(#"resultArray: %#",resultArray);
[self.objTable reloadData];
}
-(IBAction)NewFeatureButtonClk:(id)sender
{
objNewViewController=[[NewViewController alloc]initWithNibName:#"NewViewController" bundle:nil];
// Push the view controller.
[self.navigationController pushViewController:objNewViewController animated:YES];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//#warning Potentially incomplete method implementation.
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//#warning Incomplete method implementation.
// Return the number of rows in the section.
return [resultArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
objCustom = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (objCustom == nil) {
objCustom = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
//objCustom.persnName.text=[[resultArray objectAtIndex:indexPath.row]valueForKey:#"Name"];
//objCustom.persnAge.text=[[resultArray objectAtIndex:indexPath.row]valueForKey:#"Age"];
// Configure the cell...
objCustom.textLabel.text = [[resultArray objectAtIndex:indexPath.row] valueForKey:#"FeatureTitle"];
objCustom.detailTextLabel.text = [[resultArray objectAtIndex:indexPath.row] valueForKey:#"Description"];
return objCustom;
}
#pragma mark - Table view delegate
// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here, for example:
// Create the next view controller.
detailViewController = [[DetailViewController alloc]initWithNibName:#"DetailViewController" bundle:nil];
detailViewController.objData=[resultArray objectAtIndex:indexPath.row];
// Pass the selected object to the new view controller.
// Push the view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
#import <UIKit/UIKit.h>
#import "DetailData.h"
#interface DetailViewController : UIViewController
{
DetailData *objData;
}
#property(strong,nonatomic)IBOutlet UITextField *usecaseTF;
#property(strong,nonatomic)IBOutlet UITextView *featureTF;
#property(strong,nonatomic)IBOutlet UILabel *priority;
#property(strong,nonatomic)IBOutlet UIButton *voteBtn;
#property(strong,nonatomic)IBOutlet DetailData *objData;
-(IBAction)voteBtnClk:(id)sender;
#end
#import "DetailViewController.h"
#interface DetailViewController ()
#end
#implementation DetailViewController
#synthesize objData,usecaseTF,featureTF,priority,voteBtn;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
usecaseTF.text=objData.usecaseTF;
featureTF.text=objData.featureTF;
priority.text=objData.priority;
}
-(IBAction)voteBtnClk:(id)sender
{
if ([voteBtn.currentImage isEqual:#"BtnGreen.png"])
{
[voteBtn setImage:[UIImage imageNamed:#"BtnBlack.png"] forState:UIControlStateNormal];
}
else
{
[voteBtn setImage:[UIImage imageNamed:#"BtnGreen.png"] forState:UIControlStateNormal];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
#import <UIKit/UIKit.h>
#interface NewViewController : UIViewController<UITextFieldDelegate>
{
UITextField *currentTF;
}
#property(strong,nonatomic) IBOutlet UITextField *nameTF;
#property(strong,nonatomic)IBOutlet UITextField *emailTF;
#property(strong,nonatomic)IBOutlet UITextField *featureTF;
#property(strong,nonatomic)IBOutlet UITextField *descpTF;
#property(strong,nonatomic)IBOutlet UITextView *UsecaseTV;
#property(strong,nonatomic)IBOutlet UIButton *HighBtn;
#property(strong,nonatomic)IBOutlet UIButton *LowBtn;
#property(strong,nonatomic)IBOutlet UIButton *MediumBtn;
-(IBAction)sendRequestBtnClk:(id)sender;
-(IBAction)RadioBtnHigh:(id)sender;
-(IBAction)RadioBtnLow:(id)sender;
-(IBAction)RadioBtnMedium:(id)sender;
-(void)radioBtnClick;
#end
#import "NewViewController.h"
#interface NewViewController ()
#end
#implementation NewViewController
#synthesize nameTF,emailTF,featureTF,descpTF,UsecaseTV,LowBtn,HighBtn,MediumBtn;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
self.title=#"Did I Know This";
currentTF=[[UITextField alloc]init];
[ self radioBtnClick];
}
-(IBAction)sendRequestBtnClk:(id)sender
{
if (nameTF.text.length==0)
{
[self showAlertMessage:#"Please enter Your Name"];
// return NO;
}
else if (emailTF.text.length==0)
{
[self showAlertMessage:#"Please enter email ID"];
}
if (emailTF.text.length==0)
{
[self showAlertMessage:#"Please enter email address"];
}
else if ([self emailValidation:emailTF.text]==NO)
{
[self showAlertMessage:#"Please enter valid email address"];
}
else if(featureTF.text.length==0)
{
[self showAlertMessage:#"Please Confirm the Feature title"];
}
}
-(BOOL) emailValidation:(NSString *)emailTxt
{
NSString *emailRegex = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegex];
return [emailTest evaluateWithObject:emailTxt];
}
-(void)showAlertMessage:(NSString *)msg
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Note" message:msg delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
#pragma mark TextField Delegates
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[currentTF resignFirstResponder];
return YES;
}
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
currentTF = textField;
[self animateTextField:textField up:YES];
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
currentTF = textField;
[self animateTextField:textField up:NO];
}
-(void)animateTextField:(UITextField*)textField up:(BOOL)up
{
int movementDistance = 0; // tweak as needed
if (textField.tag==103||textField.tag==104||textField.tag==105||textField.tag==106)
{
movementDistance = -130;
}
else if (textField.tag==107||textField.tag==108)
{
movementDistance = -230;
}
else
{
movementDistance = 00;
}
const float movementDuration = 0.3f; // tweak as needed
int movement = (up ? movementDistance : -movementDistance);
[UIView beginAnimations: #"animateTextField" context: nil];
[UIView setAnimationBeginsFromCurrentState: YES];
[UIView setAnimationDuration: movementDuration];
self.view.frame = CGRectOffset(self.view.frame, 0, movement);
[UIView commitAnimations];
}
-(void)radioBtnClick
{
if ([HighBtn.currentImage isEqual:#"radiobutton-checked.png"])
{
[LowBtn setImage:[UIImage imageNamed:#"radiobutton-checked.png"] forState:UIControlStateNormal];
[MediumBtn setImage:[UIImage imageNamed:#"radiobutton-unchecked.png"] forState:UIControlStateNormal];
[HighBtn setImage:[UIImage imageNamed:#"radiobutton-unchecked.png"] forState:UIControlStateNormal];
}
else
{
[LowBtn setImage:[UIImage imageNamed:#"radiobutton-unchecked.png"] forState:UIControlStateNormal];
[HighBtn setImage:[UIImage imageNamed:#"radiobutton-checked.png"] forState:UIControlStateNormal];
[MediumBtn setImage:[UIImage imageNamed:#"radiobutton-unchecked.png"] forState:UIControlStateNormal];
}
}
-(IBAction)RadioBtnHigh:(id)sender
{
[LowBtn setImage:[UIImage imageNamed:#"radiobutton-checked.png"] forState:UIControlStateNormal];
[HighBtn setImage:[UIImage imageNamed:#"radiobutton-unchecked.png"] forState:UIControlStateNormal];
[MediumBtn setImage:[UIImage imageNamed:#"radiobutton-unchecked.png"] forState:UIControlStateNormal];
}
-(IBAction)RadioBtnLow:(id)sender
{
[LowBtn setImage:[UIImage imageNamed:#"radiobutton-unchecked.png"] forState:UIControlStateNormal];
[HighBtn setImage:[UIImage imageNamed:#"radiobutton-checked.png"] forState:UIControlStateNormal];
[MediumBtn setImage:[UIImage imageNamed:#"radiobutton-unchecked.png"] forState:UIControlStateNormal];
}
-(IBAction)RadioBtnMedium:(id)sender
{
[LowBtn setImage:[UIImage imageNamed:#"radiobutton-unchecked.png"] forState:UIControlStateNormal];
[HighBtn setImage:[UIImage imageNamed:#"radiobutton-unchecked.png"] forState:UIControlStateNormal];
[MediumBtn setImage:[UIImage imageNamed:#"radiobutton-checked.png"] forState:UIControlStateNormal];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
#import <UIKit/UIKit.h>
#interface CustomCellVC : UITableViewCell
#property (strong,nonatomic) IBOutlet UIImageView *persnImage;
#property (strong,nonatomic) IBOutlet UIButton *thumbImage;
#property (strong,nonatomic) IBOutlet UIImageView *calenderImage;
#property (strong,nonatomic) IBOutlet UIButton *voteImage;
#property (strong,nonatomic) IBOutlet UIButton *selectImage;
#property (strong,nonatomic) IBOutlet UILabel *publabel;
#property (strong,nonatomic) IBOutlet UILabel *IdLabel;
#property (strong,nonatomic) IBOutlet UILabel *decpLabel;
#property (strong,nonatomic) IBOutlet UITextField *ansTF;
#end
#import "CustomCellVC.h"
#implementation CustomCellVC
#synthesize ansTF,persnImage,publabel,thumbImage,calenderImage,voteImage,selectImage,IdLabel,decpLabel;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
#end
#synthesize ObjFirstVC,objNavc;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
ObjFirstVC=[[FirstVC alloc ]initWithNibName:#"FirstVC" bundle:nil];
objNavc=[[UINavigationController alloc]initWithRootViewController:ObjFirstVC];
[self.window addSubview:objNavc.view];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
#import <Foundation/Foundation.h>
#interface DetailData : NSObject
#property(strong,nonatomic)IBOutlet UITextField *usecaseTF;
#property(strong,nonatomic)IBOutlet UITextView *featureTF;
#property(strong,nonatomic)IBOutlet UILabel *priority;
#property(strong,nonatomic)IBOutlet UIButton *voteBtn;
#end

iOS partial screen dialog for drop down listbox (android spinner) style control

In iOS for the iPhone I want to make a control with similar appearance and behavior to the android spinner control when configured to behave like a drop down list box. Specifically when pressed a modal list of text options with radio buttons comes up and when one of them is pressed the list disappears and the control updates to that choice. Example:
So far I have seen a full-screen option using [self presentViewController...] with a custom ViewController but I want a partial screen (like pictured above) solution. Does anyone know how to do this or could point in the right direction.
The native solution to this will be a UIActionSheet which on iPhone will appear from the bottom and be partial screen or on iPad be very similar to the android version.
You can find the documentation here: UIActionSheet
if you didnt want to use the UIActionSheet and you wanted to make it reusable rather than adding a whole bund of UIViews to your current XIB, you could create a custom UIView with whatever interface you would need to populate it and use the interface builder to help make it look ok.
that view could have a message handler that posts the response that you would need to listen for.
then just init and load the view into your subviews and populate it
then post a message from the custom view to the handler you registered
so for your custom view you would have something like this.
#implementation SomeCustomView
+(SomeCustomView*)viewFromNibNamed:(NSString *)nibName{
NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:nibName owner:self options:NULL];
NSEnumerator *nibEnumerator = [nibContents objectEnumerator];
SomeCustomView *customView = nil;
NSObject* nibItem = nil;
while ((nibItem = [nibEnumerator nextObject]) != nil) {
if ([nibItem isKindOfClass:[AADropDown class]]) {
customView = (SomeCustomView*)nibItem;
break;
}
}
return customView;
}
-(void)someInitializationWith:(NSArray*)repeatableData andNotificationId:(NSString*)noteId{
//set your stuff up for the view here and save the notification id
}
...
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[[NSNotificationCenter defaultCenter] postNotificationName:Your_Notification_Id object:somevalue];
}
#end
and include other things, like in this case the tableview stuff or any other logic.
then in your viewcontroller you could call it like
__block id observer = [[NSNotificationCenter defaultCenter] addObserverForName:#"customViewAction" object:nil queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification *note) {
//deal with notification here
[[NSNotificationCenter defaultCenter] removeObserver: observer];
}];
SomeCustomView *cv =(SomeCustomView*) [SomeCustomView viewFromNibNamed:#"SomeCustomView"];
[cv someInitializationWith:arrayOptions andNotificationId:#"customViewAction"];
[self.view addSubview:cv];
and in your interface builder you will just need to make sure that the class of the view is set to your class type.
then you can easily reuse this code again whenever a user needs to select something else in the same manner.
Here is a variation on the solution suggested by AtomRiot.
On your view (xib or storyboard) make a button and assign this graphic to it. Don't worry if it appears stretched out in the editor. The code will make it a realizable graphic.
2X version
Then include the following files in your project (copied below):
DDLBHelper.h
DDLBHelper.m
Then in your ViewController's .h file make links to the button:
#property (weak, nonatomic) IBOutlet UIButton *ddlbB;
- (IBAction)ddlbBClick:(id)sender;
In you ViewController's .m file make the following calls:
#synthesize ddlbB, choiceLabel;
DDLBHelper *mDDLBH;
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *strings = [[NSArray alloc] initWithObjects:#"Item 1", #"Item 2", #"Item 3", nil];
mDDLBH = [[DDLBHelper alloc] initWithWithViewController:self button:ddlbB stringArray:strings currentValue:1];
}
- (IBAction)ddlbBClick:(id)sender {
[mDDLBH popupList];
}
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
[mDDLBH adjustToRotation];
}
Works just like android.
Here are the files:
DDLBHelper.h
// DDLBHelper.h
// Created by MindSpiker on 9/27/12.
#import <Foundation/Foundation.h>
#protocol DDLBHelperDelegate <NSObject>
#required
- (void) itemSelected: (int)value;
#end
#interface DDLBHelper : UIViewController <UITableViewDelegate, UITableViewDataSource>{
id <DDLBHelperDelegate> delegate;
}
#property (retain) id delegate;
// external interface
- (id) init;
- (id) initWithWithViewController:(UIViewController *)viewController button:(UIButton *)button stringArray:(NSArray *)values currentValue:(int) currentValue;
- (void) popupList;
- (BOOL) isShown;
- (void) adjustToRotation;
- (int) getValue;
- (NSString *)getValueText;
#end
DDLBHelper.m
// DDLBHelper.m
// Created by MindSpiker on 9/27/12.
#import "DDLBHelper.h"
#import <QuartzCore/QuartzCore.h>
#interface DDLBHelper () {
#private
UIViewController *mVC;
UIButton *mButton;
NSArray *mValues;
int mValue;
UITableView *mTV;
UIView *mBackgroundV;
}
#end
#implementation DDLBHelper
#synthesize delegate;
- (id) init {
self = [super init];
mVC = nil;
mButton = nil;
mValues = nil;
mValue = -1;
return self;
}
- (id) initWithWithViewController:(UIViewController *)viewController button:(UIButton *)button stringArray:(NSArray *)values currentValue:(int) currentValue {
self = [super init];
// save pointers
mVC = viewController;
mButton = button;
mValues = values;
mValue = currentValue;
[self setupButton];
return self;
}
- (void) popupList{
if (mBackgroundV == nil){
mBackgroundV = [self setupBackgroundView];
[mVC.view addSubview:mBackgroundV];
}
if (mTV == nil){
mTV = [self setupTableView];
[mVC.view addSubview:mTV];
}
[mTV reloadData];
[mBackgroundV setHidden:NO];
[mTV setHidden:NO];
}
- (BOOL) isShown{
return !mTV.isHidden;
}
- (void) adjustToRotation{
BOOL isShown = [self isShown];
// remove the controls
if (mBackgroundV != nil){
[mBackgroundV removeFromSuperview];
mBackgroundV = nil;
}
if (mTV != nil){
[mTV removeFromSuperview];
mTV = nil;
}
if (isShown){
[self popupList];
}
}
- (int) getValue{
return mValue;
}
- (NSString *) getValueText{
if (mValues != nil && mValue > -1) {
if (mValues.count > mValue){
return [mValues objectAtIndex:mValue];
}
}
return nil;
}
- (void) updateButtonTitle{
NSString *title = [NSString stringWithFormat:#" %#", [self getValueText]];
[mButton setTitle:title forState:UIControlStateNormal];
}
- (void) setupButton {
UIImage *buttonBG = [UIImage imageNamed:#"sis_proceeds_ddlb.png"];
UIEdgeInsets insets = UIEdgeInsetsMake(8, 8, 8, 45);
UIImage *sizableImg = [buttonBG resizableImageWithCapInsets:insets];
[mButton setBackgroundImage:sizableImg forState:UIControlStateNormal];
[mButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[self updateButtonTitle];
}
- (UIView *) setupBackgroundView{
UIView *v = [[UIView alloc] initWithFrame:mVC.view.bounds];
[[v layer] setOpaque:NO];
[[v layer] setOpacity:0.7f];
[[v layer] setBackgroundColor:[UIColor blackColor].CGColor];
return v;
}
- (UITableView *) setupTableView {
CGRect rect = [self makeTableViewRect];
UITableView *tv = [[UITableView alloc] initWithFrame:rect style:UITableViewStylePlain];
[tv setDelegate:self];
[tv setDataSource:self];
[tv setBackgroundColor:[UIColor whiteColor]];
[[tv layer] setBorderWidth:2];
[[tv layer] setBorderColor:[UIColor lightGrayColor].CGColor];
[[tv layer] setCornerRadius:10];
[mVC.view addSubview:tv];
return tv;
}
- (CGRect) makeTableViewRect {
float l=0.0, t=0.0, w=0.0, h=0.0, maxH=0.0, cellH=0.0, cellsH=0.0;
// get
l = mButton.frame.origin.x;
w = mButton.frame.size.width;
t = mVC.view.bounds.origin.y + 50;
maxH = mVC.view.bounds.size.height - 100;
// get cell height
UITableViewCell *c = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
cellH = c.bounds.size.height;
// see if list will overlow maxH(eight)
cellsH = cellH * mValues.count;
if (cellsH > maxH) {
h = maxH;
} else {
h = cellsH;
}
return CGRectMake(l, t, w, h);
}
#pragma mark - TableView Delegate functions
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1; // this is a one section table
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return mValues.count; // should be called for only one section
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
// try to resuse a cell if possible
static NSString *RESUSE_IDENTIFIER = #"myResuseIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:RESUSE_IDENTIFIER];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:RESUSE_IDENTIFIER];
}
cell.textLabel.text = [mValues objectAtIndex:indexPath.row];
if (mValue == indexPath.row){
cell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
// save value and hide view
mValue = indexPath.row;
[self updateButtonTitle];
[mBackgroundV setHidden:YES];
[mTV setHidden:YES];
[delegate itemSelected:mValue];
}
#end

Resources