i want to display multiple images in a view controller using iCarousel.
i list all my images in NSMutableArray foto,
and then i called the array foto in iCarousel method viewForItemAtIndex.
i've followed some tutorial but still doesn't work.
please help me.
here's my .m code
#import "TestController.h"
#interface TestController () <UIActionSheetDelegate>
#property (nonatomic, retain) NSMutableArray *foto;
#end
#implementation TestController
#synthesize carousel;
#synthesize foto;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
foto = [NSArray arrayWithObjects:
[UIImage imageNamed:#"Seleb1.jpg"],
[UIImage imageNamed:#"Seleb2.jpg"],
[UIImage imageNamed:#"Seleb3.jpg"],
nil];
}
return self;
}
- (void)dealloc
{
carousel.delegate = nil;
carousel.dataSource = nil;
}
- (void)viewDidLoad
{
[super viewDidLoad];
carousel.type = iCarouselTypeCoverFlow2;
}
- (void)viewDidUnload
{
[super viewDidUnload];
self.carousel = nil;
}
#pragma mark -
#pragma mark iCarousel methods
- (NSUInteger)numberOfItemsInCarousel:(iCarousel *)carousel
{
return [foto count];
}
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
{
view = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[foto objectAtIndex:index]]];
return view;
}
#end
can someone help me ?
what is wrong with my code ?
Updated Code
#import "TestController.h"
#interface TestController ()
#property (nonatomic, retain) NSArray *foto;
#end
#implementation TestController
#synthesize carousel;
#synthesize foto;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
foto = [NSArray arrayWithObjects:
#"Seleb1.jpg",
#"Seleb2.jpg",
#"Seleb3.jpg",
nil];
}
return self;
}
- (void)dealloc
{
carousel.delegate = nil;
carousel.dataSource = nil;
}
- (void)viewDidLoad
{
[super viewDidLoad];
carousel.type = iCarouselTypeCoverFlow2;
[carousel reloadData];
}
- (void)viewDidUnload
{
[super viewDidUnload];
self.carousel = nil;
}
#pragma mark -
#pragma mark iCarousel methods
- (NSUInteger)numberOfItemsInCarousel:(iCarousel *)carousel
{
return [foto count];
}
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view {
view = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200.0f, 200.0f)]; // set the frame for your Image
UIImage *image = [UIImage imageNamed:[foto objectAtIndex:index]];
((UIImageView *)view).image = image;
return view;
}
- (CGFloat)carousel:(iCarousel *)carousel valueForOption:(iCarouselOption)option withDefault:(CGFloat)value
{
//customize carousel display
return value+0.1;
}
#end
change this line
view = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[foto objectAtIndex:index]]];
to
Reason : you have already defined your array as [UIImage imageNamed:#"Seleb1.jpg"] , so in here you need call directly like
view = [[UIImageView alloc] initWithImage:[foto objectAtIndex:index]];
Choice-2
create a array like
foto = [NSArray arrayWithObjects:
#"Seleb1.jpg",
#"Seleb2.jpg",
#"Seleb3.jpg",
nil];
and call like
view = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[foto objectAtIndex:index]]];
if you need
use this
- (void)viewDidLoad
{
[super viewDidLoad];
carousel.type = iCarouselTypeCoverFlow2;
[carousel reloadData];
}
Update answer
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view {
view = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200.0f, 200.0f)]; // set the frame for your Image
UIImage *image = [UIImage imageNamed:[foto objectAtIndex:index]];
((UIImageView *)view).image = image;
return view;
}
#TomKnapen : where should i set it ? if it's on the story board, i've
set it already. in the TestController.h, i've set it too here's my
code in .h : TestController : UIViewController – Shasapo
I'm not sure about how you are setting it in storyboard, but in code, you are not setting the delegate. This line doesn't set the delegate TestController : UIViewController <iCarouselDataSource,iCarouselDelegate>, what it does is it makes you controller, which is TestController in this case, comply to the iCarouselDelegate protocol. What you have to do is explicitly set the delegate and datasource in viewDidLoad,for example, i.e.
carousel.delegate = self;
carousel.datasource = self;
2 - try debugging those delegate methods first. Start with nimberOfItems method, check if foto array isnt nil. Then in viewForItem method check if the image that you return isn't nil.
Because you are using storyboard, your initWithNibName method not getting called, that is why you foto array not getting initialized, I assume. In my opinion your numberofitems method returns 0. Try to put breakpoint int this method and see, or just add a NSLog statement and check if foto array isnt nil
3 - You are not adding iCarousel view to your view.
I have used this framework in the past, so I decided to include a snippet of the code I implemented
#pragma mark -
#pragma mark iCarousel methods
- (void)iCarouselSetup {
self.view.backgroundColor = kAppColor;
self.carousel = [[iCarousel alloc] initWithFrame:CGRectMake(0, calendarBar.bottom + 10, self.view.width, self.view.height)];
[self.view addSubview:self.carousel];
self.carousel.delegate = self;
self.carousel.dataSource = self;
self.carousel.type = iCarouselTypeCoverFlow;
self.carousel.scrollEnabled = NO;
[self.carousel scrollToItemAtIndex:2 animated:NO];
self.currentProjectsTableview = (UITableView*)[self.carousel currentItemView]; }
- (NSInteger)numberOfItemsInCarousel:(iCarousel *)carousel {
return 5; }
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSInteger)index reusingView:(UIView *)view {
self.projectsTableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStylePlain];
self.projectsTableview.x = 0;
self.projectsTableview.y = calendarBar.bottom;
self.projectsTableview.width = [ASize screenWidth];
self.projectsTableview.height = [ASize screenHeight] - 180;
self.projectsTableview.contentInset = UIEdgeInsetsMake(0, 0, 100, 0);
self.projectsTableview.backgroundColor = [UIColor fromRGB:0xF8F8F8];
self.projectsTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
self.projectsTableview.dataSource = self;
self.projectsTableview.delegate = self;
self.projectsTableview.tag = tableTag++;
return self.projectsTableview; }
- (void)carousel:(iCarousel *)carousel didSelectItemAtIndex:(NSInteger)index {
self.carousel.scrollEnabled = NO;
[AppDelegate getDelegate].deckController.panningMode = IIViewDeckFullViewPanning;
[UIView animateWithDuration:0.3 animations:^{
for (int i = 0; i < self.carousel.numberOfItems; i++)
{
[self.carousel itemViewAtIndex:i].transform = CGAffineTransformMakeScale( 1.1f, 1.1f);
}
}completion:^(BOOL finished) {
[UIView animateWithDuration:0.2 animations:^{
for (int i = 0; i < self.carousel.numberOfItems; i++)
{
[self.carousel itemViewAtIndex:i].transform = CGAffineTransformMakeScale( 1.0f, 1.0f);
[self.carousel itemViewAtIndex:i].userInteractionEnabled = YES;
}
} ];
tableMinimized = NO;
}];
self.currentProjectsTableview = (UITableView*)[carousel itemViewAtIndex:index]; }
- (void)carouselDidEndScrollingAnimation:(iCarousel *)carousel {
[navButton setTitle:self.projectDates[self.carousel.currentItemIndex] forState:UIControlStateNormal]; }
i fix my code by combining all your answer, thankyou so much. here's my new code :
#import "TestController.h"
#interface TestController ()
#property (nonatomic, retain) NSArray *foto;
#end
#implementation TestController
#synthesize carousel;
#synthesize foto;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)dealloc
{
carousel.delegate = nil;
carousel.dataSource = nil;
}
- (void)viewDidLoad
{
carousel.delegate = self;
carousel.dataSource = self;
foto = [NSArray arrayWithObjects:
#"Seleb1.jpg",
#"Seleb2.jpg",
#"Seleb3.jpg",
nil];
[super viewDidLoad];
carousel.type = iCarouselTypeCoverFlow2;
[carousel reloadData];
}
- (void)viewDidUnload
{
[super viewDidUnload];
self.carousel = nil;
}
#pragma mark -
#pragma mark iCarousel methods
- (NSUInteger)numberOfItemsInCarousel:(iCarousel *)carousel
{
NSLog(#"%lu",(unsigned long)foto.count);
return [foto count];
}
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view {
view = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200.0f, 200.0f)]; // set the frame for your Image
UIImage *image = [UIImage imageNamed:[foto objectAtIndex:index]];
((UIImageView *)view).image = image;
return view;
}
- (CGFloat)carousel:(iCarousel *)carousel valueForOption:(iCarouselOption)option withDefault:(CGFloat)value
{
//customize carousel display
return value+0.1;
}
#end
Thank you so much for all your answer, i really appreciate it :)
Related
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
Ok, I really tried looking for an example or tutorial in how to achieve what I'm looking for, but haven't had any luck.
I have a PFQueryTableView that passes data to a DetailView (all good there).
My DetailView is a Horizontal ScrollView that gets images from the cell clicked. And here comes my problem: I manage to get the data to pass to the DetailView but I don't know how to set up the images in the ScrollView. Can anyone please send me on the direction of a tutorial or could help me via this question?
Here is my code: (Obviously I'm missing the section where you set up the images to be viewed in the ScrollView.)
BellezaTableViewController.m
#import "BellezaTableViewController.h"
#import "BellezaDetailViewController.h"
#import "BellezaView.h"
#interface BellezaTableViewController ()
#end
#implementation BellezaTableViewController {
}
- (id)initWithCoder:(NSCoder *)aCoder
{
self = [super initWithCoder:aCoder];
if (self) {
self.parseClassName = #"BellezaView";
self.textKey = #"cellTitle";
self.textKey = #"descriptionTitle";
self.pullToRefreshEnabled = YES;
self.paginationEnabled = NO;
self.loadingViewEnabled = YES;
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (PFQuery *)queryForTable{
PFQuery *query = [PFQuery queryWithClassName:self.parseClassName];
query.cachePolicy = kPFCachePolicyCacheThenNetwork;
return query;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object {
static NSString *simpleTableIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
UILabel *cellTitle = (UILabel*) [cell viewWithTag:101];
cellTitle.text = [object objectForKey:#"cellTitle"];
UILabel *descriptionTitle = (UILabel*) [cell viewWithTag:102];
descriptionTitle.text = [object objectForKey:#"descriptionTitle"];
return cell;
}
- (void) objectsDidLoad:(NSError *)error
{
[super objectsDidLoad:error];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"showBellezaDetail"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
BellezaDetailViewController *destViewController = segue.destinationViewController;
PFObject *object = [self.objects objectAtIndex:indexPath.row];
BellezaView *bellezaView = [[BellezaView alloc] init];
bellezaView.cellTitle = [object objectForKey:#"cellTitle"];
bellezaView.descriptionTitle = [object objectForKey:#"descriptionTitle"];
bellezaView.image_1 = [object objectForKey:#"image_1"];
destViewController.bellezaView = bellezaView;
}
}
#end
BellezaTableViewController.h
#import <UIKit/UIKit.h>
#import <Parse/Parse.h>
#interface BellezaTableViewController : PFQueryTableViewController
#end
DetailViewController.m
#import "BellezaDetailViewController.h"
#import "BellezaView.h"
#interface BellezaDetailViewController ()
#end
#implementation BellezaDetailViewController
#synthesize lookPhoto, bellezaView, activityIndicator, scrollView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];{
[activityIndicator startAnimating];
[activityIndicator performSelector:#selector(removeFromSuperview) withObject:nil afterDelay:60];
[scrollView setAlwaysBounceHorizontal:YES];
[scrollView setAlwaysBounceVertical:NO];
[scrollView setPagingEnabled:YES];
NSInteger numberOfViews = 3;
for (int i = 0; i < numberOfViews; i++){
This would be the section I do not know how to handle, and can't find any examples to follow through. Should I use an array? If so, how do I retrieve the data if I should have passed it from the PFQueryTable? I found some examples that get images like this code:
image.image = [UIImage imageNamed: [NSString stringWithFormat:#"image_%d", i+1]];
but my problem is that my images have to be fetched by parse. So how do I do that? Please help!
lookPhoto.file = bellezaView.image_1;
[lookPhoto loadInBackground];
[scrollView addSubview:lookPhoto];
}
scrollView.contentSize = CGSizeMake(self.view.frame.size.width * numberOfViews, self.view.frame.size.height);
}
}
- (void)viewDidUnload {
[self setLookPhoto:nil];
[super viewDidUnload];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
DetailViewController.h
#import <UIKit/UIKit.h>
#import "BellezaView.h"
#import <Parse/Parse.h>
#interface BellezaDetailViewController : UIViewController
#property (weak, nonatomic) IBOutlet PFImageView *lookPhoto;
#property (weak, nonatomic) IBOutlet UIActivityIndicatorView *activityIndicator;
#property (nonatomic, strong) BellezaView *bellezaView;
#property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
#end
BellezaView.m
#import "BellezaView.h"
#implementation BellezaView
#synthesize cellTitle, descriptionTitle, image_1;
#end
BellezaView.h
#import <Foundation/Foundation.h>
#import <Parse/Parse.h>
#interface BellezaView : NSObject
#property (nonatomic, strong) NSString *cellTitle;
#property (nonatomic, strong) NSString *descriptionTitle;
#property (nonatomic, strong) PFFile *image_1;
#end
Thanks in advance!
If you have a link to the image as a property in your PFObject you can do something like
PFFile* imageFile = [object objectForKey:#"imageFile"];
UIImage* img = nil;
if (startImage != nil)
{
img = [[UIImage alloc] initWithData:[imgFile getData]];
}
The property "imageFile" is link to the image in Parse
Keep in mind that this makes a network call and so you should not do this on the main thread
Found a way, Here is my code for the DetailViewController.m file:
Hope it helps anyone in need! :)
- (void)viewDidLoad {
[super viewDidLoad];
//Do any additional setup after loading the view.
[activityIndicator startAnimating];
[activityIndicator performSelector:#selector(removeFromSuperview) withObject:nil afterDelay:60];
scrollView.pagingEnabled = YES;
[UIView animateWithDuration:20 animations:^{ScrollNext.alpha = 0.0;}];
NSInteger numberOfViews = 10;
for (int i = 0; i < numberOfViews; i++) {
PFImageView *lookView1 = [[PFImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
lookView1.image = [UIImage imageNamed:#"Lading.jpg"];
lookView1.file = bellezaView.image_1;
[scrollView addSubview:lookView1];
[lookView1 loadInBackground:^(UIImage *image, NSError *error) {
if (!error) {
lookView1.frame = CGRectMake(0,0,self.view.frame.size.width, self.view.frame.size.height);
lookView1.contentMode = UIViewContentModeScaleAspectFit;
scrollView.contentSize = CGSizeMake(self.view.frame.size.width * numberOfViews, self.view.frame.size.height);
}
}];
PFImageView *lookView2 = [[PFImageView alloc] init];
lookView2.frame = CGRectMake(lookView1.frame.size.width*1, 0, 320, 500);
lookView2.file = bellezaView.image_2;
[scrollView addSubview:lookView2];
[lookView2 loadInBackground:^(UIImage *image, NSError *error) {
if (!error) {
lookView2.contentMode = UIViewContentModeScaleAspectFit;
lookView2.frame = CGRectMake(lookView1.frame.size.width*1, 0, self.view.frame.size.width, self.view.frame.size.height);
}
}];
PFImageView *lookView3 = [[PFImageView alloc] init];
lookView3.frame = CGRectMake(lookView1.frame.size.width*2, 0, 320, 500);
lookView3.file = bellezaView.image_3;
[scrollView addSubview:lookView3];
[lookView3 loadInBackground:^(UIImage *image, NSError *error) {
if (!error) {
lookView3.contentMode = UIViewContentModeScaleAspectFit;
lookView3.frame = CGRectMake(lookView1.frame.size.width*2, 0, self.view.frame.size.width, self.view.frame.size.height);
}
}];
//Insert Another View
}
}
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.
My source code download
------Updated--------
I am trying to implement a sidebar effect using CGAffineTransformMakeTranslate simulate slide-in and slide-out. I want to make my sidebar as a scrollview so it could be add more data but it can not scroll at all.
Here is my code:
SidebarView is a UITableView
#import "SidebarView.h"
#interface SidebarView ()
#property (nonatomic, readwrite) CGFloat offsetX;
#end
#implementation SidebarView
#pragma mark - Initilization
- (void)setup {
// do initilization here
self.offsetX = self.frame.size.width;
[self registerClass:[UITableViewCell class] forCellReuseIdentifier:#"sidebarCell"];
}
- (void)awakeFromNib {
[self setup];
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
[self setup];
return self;
}
#pragma mark - Custom function
- (void)show {
self.transform = CGAffineTransformMakeTranslation(-self.offsetX, 0);
}
- (void)hide {
self.transform = CGAffineTransformMakeTranslation(-self.offsetX, 0);
}
And my view controller:
#import "ViewController.h"
#import "SidebarView.h"
#interface ViewController () <UITableViewDataSource>
#property (nonatomic) BOOL isMenuHide;
#property (nonatomic, strong) SidebarView *sidebarView;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.isMenuHide = YES;
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
if (self.sidebarView) {
self.sidebarView = nil;
}
if (self.view) {
self.view = nil;
}
}
- (SidebarView *)sidebarView {
if (!_sidebarView) {
CGRect frame = [[UIScreen mainScreen] bounds];
frame.size.width /= 2;
_sidebarView = [[SidebarView alloc] initWithFrame:frame];
_sidebarView.transform = CGAffineTransformMakeTranslation(-_sidebarView.offsetX, 0);
_sidebarView.contentSize = CGSizeMake(320, 960);
_sidebarView.scrollEnabled = YES;
_sidebarView.showsVerticalScrollIndicator = YES;
_sidebarView.dataSource = self;
}
return _sidebarView;
}
#define ANIMATE_DURATION 0.5
- (IBAction)showMenu:(UIBarButtonItem *)sender {
if (self.isMenuHide) {
[self.view addSubview:self.sidebarView];
[UIView animateWithDuration:ANIMATE_DURATION animations:^{
[self.sidebarView show];
self.view.transform = CGAffineTransformMakeTranslation(self.sidebarView.offsetX, 0);
}];
} else {
[UIView animateWithDuration:ANIMATE_DURATION animations:^{
[self.sidebarView hide];
self.view.transform = CGAffineTransformMakeTranslation(0, 0);
} completion:^(BOOL finished) {
[self.sidebarView removeFromSuperview];
}];
}
self.isMenuHide = !self.isMenuHide;
}
#pragma mark - UITableView Datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 11;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"sidebarCell"];
cell.textLabel.text = #"Bingo";
return cell;
}
#end
Please tell my "why my scrollview cannot scroll" thanks.
contentSize needs to be set to the size of the content being contained, not the size of the frame in which it sits.
I don't know if your code has other problems, but that's the most terminal one.
I'm setting the backgroundColor of my UITableViewCell like this:
cell.backgroundColor = [UIColor colorWithPatternImage:
[UIImage imageNamed:#"background.png"]];
It looks fine except for the "end caps" of the cell. The end caps (where the rounded corners start) are colored differently like the middle portion of the cell. Do I need to provide images for the end caps too?
not really sure what the end caps are. but i would say if ur using an image for your cell it should take up the whole cell. and you should be defining the size of your cells at that point. see layout subviews below for what i mean
#import "CustomCell.h"
#implementation CustomCell
#synthesize primaryLabel,myImageView;
- (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) {
// Initialization code
primaryLabel = [[UILabel alloc]init];
primaryLabel.textAlignment = UITextAlignmentLeft;
primaryLabel.font = [UIFont systemFontOfSize:20];
myImageView = [[UIImageView alloc]init];
[self.contentView addSubview:primaryLabel];
[self.contentView addSubview:myImageView];
}
return self;
}
- (void)layoutSubviews {
[super layoutSubviews];
CGRect contentRect = self.contentView.bounds;
CGFloat boundsX = contentRect.origin.x;
CGRect frame;
frame= CGRectMake(boundsX+10 ,0, 40, 40);
myImageView.frame = frame;
frame= CGRectMake(boundsX+70 ,5, 200, 25);
primaryLabel.frame = frame;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)dealloc
{
[myImageView release];
[primaryLabel release];
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
#end