I am using this code from the link...Which is the best approach for creating custom tab bar controller?
now I need to hide tabbar inbetween a page. and on the next page it will appear as usual. how to do it if any one can please help me with some useable link or codes
#import "MyTabBarController.h"
#interface MyTabBarController ()
#property (strong, nonatomic) UIButton *btn1;
#property (strong, nonatomic) UIButton *btn2;
#property (strong, nonatomic) UIButton *btn3;
#property (strong, nonatomic) UIButton *btn4;
#property (weak, nonatomic) UIButton *lastSender;
#property (strong, nonatomic) UIView *tabbarView;
#end
#implementation MyTabBarController
-(id)init
{
if (self=[super init]) {
[self setUP];
}
return self;
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
if (self=[super initWithCoder:aDecoder]) {
[self setUP];
}
return self;
}
-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
if (self=[super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
[self setUP];
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
_tabbarView = [[[NSBundle mainBundle] loadNibNamed:#"MyTabBarController" owner:nil options:nil] lastObject];
_tabbarView.frame = CGRectMake(0.0,
[[UIScreen mainScreen] bounds].size.height-70,
[[UIScreen mainScreen] bounds].size.width,70); // make it overlay your actual tab bar
[self.view addSubview:_tabbarView];
_btn1 = (UIButton *)[_tabbarView viewWithTag:1];
[_btn1 addTarget:self action:#selector(processBtn:) forControlEvents:UIControlEventTouchUpInside];
_btn2 = (UIButton *)[_tabbarView viewWithTag:2];
[_btn2 addTarget:self action:#selector(processBtn:) forControlEvents:UIControlEventTouchUpInside];
_btn3 = (UIButton *)[_tabbarView viewWithTag:3];
[_btn3 addTarget:self action:#selector(processBtn:) forControlEvents:UIControlEventTouchUpInside];
_btn4 = (UIButton *)[_tabbarView viewWithTag:4];
[_btn4 addTarget:self action:#selector(processBtn:) forControlEvents:UIControlEventTouchUpInside];
_lastSender = _btn4;
[self setSelectedViewController:self.viewControllers[3]];
}
-(void)processBtn:(id)sender
{
_lastSender =(UIButton*) sender;
[self setSelectedViewController:[self.viewControllers objectAtIndex:_lastSender.tag - 1]];
}
- (void)setSelectedViewController:(UIViewController *)selectedViewController
{
if ([self.viewControllers indexOfObject:selectedViewController] == 0)
{
if (self.selectedViewController == selectedViewController)
{
[(UINavigationController *)self.selectedViewController popToRootViewControllerAnimated:YES]; // pop to root if tapped the same controller twice
}
[super setSelectedViewController:selectedViewController];
}else if ([self.viewControllers indexOfObject:selectedViewController] == 1)
{
if (self.selectedViewController == selectedViewController)
{
[(UINavigationController *)self.selectedViewController popToRootViewControllerAnimated:YES]; // pop to root if tapped the same controller twice
}
[super setSelectedViewController:selectedViewController];
}else if ([self.viewControllers indexOfObject:selectedViewController] == 2)
{
if (self.selectedViewController == selectedViewController)
{
[(UINavigationController *)self.selectedViewController popToRootViewControllerAnimated:YES]; // pop to root if tapped the same controller twice
}
[super setSelectedViewController:selectedViewController];
}else if ([self.viewControllers indexOfObject:selectedViewController] == 3)
{
if (self.selectedViewController == selectedViewController)
{
[(UINavigationController *)self.selectedViewController popToRootViewControllerAnimated:YES]; // pop to root if tapped the same controller twice
}
[super setSelectedViewController:selectedViewController];
}
NSLog(#"%#",[_tabbarView subviews]);
for (UIButton *btn in [_tabbarView subviews])
{
if ([btn isKindOfClass:[UIButton class]])
{
if (btn == _lastSender)
{
NSString *strImageName=#"";
switch (btn.tag)
{
case 1:
strImageName=#"settings_icon_hover.png";
break;
case 2:
strImageName=#"garage_icon_hover.png";
break;
case 3:
strImageName=#"help_icon_hover.png";
break;
case 4:
strImageName=#"new_test_hover.png";
break;
default:
break;
}
btn.selected = YES;
UIImageView *imgSelected=(UIImageView*)[_tabbarView viewWithTag:btn.tag*10];
[imgSelected setImage:[UIImage imageNamed:strImageName]];
UILabel *lblSelected=(UILabel*)[_tabbarView viewWithTag:btn.tag*100];
[lblSelected setTextColor:[UIColor colorWithRed:82.0f/255.0f green:160.0f/255.0f blue:205.0f/255.0f alpha:1.0f]];
}
else
{
btn.selected = NO;
NSString *strImageName=#"";
switch (btn.tag)
{
case 1:
strImageName=#"settings_icon.png";
break;
case 2:
strImageName=#"garage_icon.png";
break;
case 3:
strImageName=#"help_icon.png";
break;
case 4:
strImageName=#"new_test.png";
break;
default:
break;
}
UIImageView *imgNonSelected=(UIImageView*)[_tabbarView viewWithTag:btn.tag*10];
[imgNonSelected setImage:[UIImage imageNamed:strImageName]];
UILabel *lblSelected=(UILabel*)[_tabbarView viewWithTag:btn.tag*100];
[lblSelected setTextColor:[UIColor grayColor]];
}
}
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)setUP
{
NSMutableArray *viewControllers = [NSMutableArray array];
UIStoryboard *storyBoard=[UIStoryboard storyboardWithName:#"Main" bundle:nil];
UINavigationController *navControllerSettings=[storyBoard instantiateViewControllerWithIdentifier:#"settings"];
[viewControllers addObject:navControllerSettings];
UINavigationController *navControllerGarage=[storyBoard instantiateViewControllerWithIdentifier:#"garage"];
[viewControllers addObject:navControllerGarage];
UINavigationController *navControllerHelp=[storyBoard instantiateViewControllerWithIdentifier:#"help"];
[viewControllers addObject:navControllerHelp];
UINavigationController *navControllerNewTest=[storyBoard instantiateViewControllerWithIdentifier:#"newtest"];
[viewControllers addObject:navControllerNewTest];
self.viewControllers = viewControllers;
}
#end
Related
In building a custom NSButton, I've run into a problem handling highlight behavior. After clicking down on the button, holding, and dragging the cursor outside the button's bounds, mouseExited: and mouseEntered: events are not delivered. I understand the reason why, because in mouseDown: calling [super mouseDown:event]; will block until the click is released.
In researching this I came across this Stack Overflow post which describes the same problem. The solution noted is to add NSTrackingEnabledDuringMouseDrag to the NSTrackingArea options, which I have done, yet I continue to see this problem. I tried the other proposed solution with handling the next events in a loop, but this resulted in odd behavior. The button text color turns black on mouse down instead of highlighting the dimmed color, and it doesn't unhighlight upon releasing the mouse, it remains black.
I am using Xcode 9.3, running on macOS 10.13.4.
Here is my NSButton subclass:
#interface BorderlessButton : NSButton {
NSColor *_tempColor;
}
#property (strong, nonatomic) NSColor *color;
#end
#interface BorderlessButton ()
#property (nonatomic) BOOL pressed;
#end
#implementation BorderlessButton
- (id)init {
if (self = [super init]) {
[self setUp];
}
return self;
}
- (id)initWithFrame:(NSRect)frameRect {
if (self = [super initWithFrame:frameRect]) {
[self setUp];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super initWithCoder:aDecoder]) {
[self setUp];
}
return self;
}
- (void)setUp {
_color = [NSColor redColor];
[self setTitle:self.title];
[self setButtonType:NSButtonTypeMomentaryChange];
[self setBordered:NO];
NSTrackingArea *area = [[NSTrackingArea alloc] initWithRect:self.bounds
options:NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways | NSTrackingEnabledDuringMouseDrag
owner:self
userInfo:nil];
[self addTrackingArea:area];
}
- (void)setTitle:(NSString *)title {
[super setTitle:title];
NSMutableAttributedString *colorTitle = [[NSMutableAttributedString alloc] initWithAttributedString:[self attributedTitle]];
[colorTitle addAttributes:#{NSFontAttributeName: self.font, NSForegroundColorAttributeName: self.color} range:NSMakeRange(0, [colorTitle length])];
[self setAttributedTitle:colorTitle];
}
- (void)setColor:(NSColor *)color {
_color = color;
[self setTitle:self.title];
}
- (void)mouseDown:(NSEvent *)event {
self.pressed = YES;
[self highlight:YES];
[super mouseDown:event]; // this blocks until released
[self mouseUp:event];
}
- (void)mouseUp:(NSEvent *)event {
self.pressed = NO;
[self highlight:NO];
[super mouseUp:event];
}
//FIXME: Not called after mouse press down and hold then exit
- (void)mouseExited:(NSEvent *)event {
if (self.pressed) {
[self highlight:NO];
}
[super mouseExited:event];
}
- (void)mouseEntered:(NSEvent *)event {
if (self.pressed) {
[self highlight:YES];
}
[super mouseEntered:event];
}
- (void)highlight:(BOOL)flag {
if (flag) {
if (self.isEnabled) {
NSColor *dimmedColor = [self dimmedColor];
_tempColor = _color;
self.color = dimmedColor;
[self setTitle:self.title];
}
} else {
if (self.isEnabled) {
self.color = _tempColor;
[self setTitle:self.title];
}
}
}
- (NSColor *)dimmedColor {
return [self.color colorWithAlphaComponent:0.5];
}
#end
I was wondering how to set the progress bar equal to max user input in xcode.
#property (weak, nonatomic) IBOutlet UIProgressView *progressBar;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_inputAmount.keyboardType = UIKeyboardTypeDecimalPad;
self.amount = [NSMutableArray new];
[self.amount addObject:#"Total Amount of Push-Ups:"];
[self.myList setDataSource:self];
_inputAmount = UIProgressViewStyleBar;
}
This is just a snipet of my code, the inputamount = progress bar is what I want to do, but I'm not really sure how to do it. I want the greatest input amount the be equal to the progressviewbar as well. So i would have to compare all the #s that were added to the array. Any ideas? Thanks!
//
// ViewController.m
// Push Up Tracker
//
// Created by Paul Lesny on 10/26/14.
// Copyright (c) 2014 Paul Lesny. All rights reserved.
//
#import "ViewController.h"
#interface ViewController ()
#property (weak, nonatomic) IBOutlet UITextField *inputAmount;
#property (weak, nonatomic) IBOutlet UIButton *addButton;
#property NSMutableArray *amount;
#property (weak, nonatomic) IBOutlet UITableView *myList;
#property (weak, nonatomic) IBOutlet UIProgressView *progressBar;
#end
#implementation ViewController
//#synthesize progressBar, progressValue;
///NSInteger stringToInt(NSString *string) {
//return [string integerValue];
//}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_inputAmount.keyboardType = UIKeyboardTypeDecimalPad;
self.amount = [NSMutableArray new];
[self.myList setDataSource:self];
[self readDataFromFile:#"lalala1"];
if (_amount.count!=0)
{
NSMutableDictionary *max=[_amount objectAtIndex:0];
NSString *m = max[#"max"];
NSLog (#"%#",m);
NSInteger num=[m intValue];
NSLog(#"amount is not empty");
_progressBar.progress = (float) [m intValue]/50;
}
else
{
_progressBar.progress=0;
}
//[self.amount addObject:#"0"];
//[self.myList reloadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return[self.amount count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString * cellId = #"pancake";//identifier for the cells
// get a cell from the cache
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
// if the cell is not cached then
if(cell ==nil)
{
// create a new cell
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
}
NSMutableDictionary *newEntry=_amount[indexPath.row];
[cell.textLabel setText:newEntry[#"pushUpNum"]];
// put the corresponding element of the array as text.
// return the cell.
return cell;
}
-(BOOL) textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
-(void) readDataFromFile:(NSString*)fileName
{
NSData *fileData=[NSData dataWithContentsOfURL:[self urlOfEntries:#"lalala1"]];
if(fileData!=nil)
{
_amount=[NSPropertyListSerialization
propertyListWithData:fileData options:
NSPropertyListMutableContainers format:nil error:nil];
}
else
{
_amount=[NSMutableArray new];
}
}
-(NSURL *) urlOfEntries:(NSString*)name
{
NSURL *docDirectory=[[[NSFileManager defaultManager]
URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask]lastObject];
NSURL* fullPath=[docDirectory URLByAppendingPathComponent:name];
return fullPath;
}
-(void) savePushUpTotal:(NSMutableArray *)myEntries
{
[myEntries writeToURL:[self urlOfEntries:#"lalala1"]atomically:YES];
}
- (IBAction)sender:(id)addButton
{
NSMutableDictionary *newRecord = [[NSMutableDictionary alloc]init];
[newRecord setObject:self.inputAmount.text forKey:#"pushUpNum"];
if (_amount.count==0)
{
[newRecord setObject:#"0" forKey:#"max"];
}
[self.amount addObject:newRecord];
[self savePushUpTotal:_amount];
[self.myList reloadData];
[self.inputAmount resignFirstResponder];
[self savePushUpTotal:_amount];
NSMutableDictionary *max=_amount[0];
NSString *m = max[#"max"];
NSInteger num=[m intValue];
NSMutableDictionary *newDictionary=_amount[_amount.count-1];
NSString *blah = newDictionary[#"pushUpNum"];
NSInteger number=[blah intValue];
NSLog(#"dadala%#",blah);
if (_amount.count!=1)
{
if (number>num)
{
_progressBar.progress= (float)number/50;
NSString *pushUp = max[#"pushUpNum"];
NSMutableDictionary *maxPush = [[NSMutableDictionary alloc]init];
[maxPush setObject:pushUp forKey:#"pushUpNum"];
[maxPush setObject:blah forKey:#"max"];
[_amount removeObjectAtIndex:(NSUInteger)0];
[_amount insertObject:maxPush atIndex:0];
[self savePushUpTotal:_amount];
}
}
else
{
_progressBar.progress = (float)number/50;
}
}
- (IBAction)clear:(UIButton *)sender
{
_progressBar.progress=0;
[_amount removeAllObjects];
[[NSUserDefaults standardUserDefaults] setObject:_amount forKey:0];
[_myList reloadData];
}
#end
In Mavericks, the methods to open and close NSSheets has changed. And to make it tougher, the Release Notes do not match the current documentation (see below).
I'm trying to do this:
MainSheetController (NSWindowController):
-(IBAction)callSheet:(id)sender {
[sheetController openSheet];
}
SheetController (NSObject):
(void)openSheet {
[[NSBundle mainBundle] loadNibNamed:sheetName owner:self topLevelObjects:nil];
NSLog(#"1");
[self.mainWindowController.window beginSheet:self.sheet completionHandler:nil];
NSLog(#"2");
}
I get to 2, with no errors or warnings, but no sheet..
Current Documentation:
#if NS_BLOCKS_AVAILABLE
- (void)beginSheet:(NSWindow *)sheetWindow completionHandler:(void (^)(NSModalResponse returnCode))handler NS_AVAILABLE_MAC(10_9);
- (void)beginCriticalSheet:(NSWindow *)sheetWindow completionHandler:(void (^)(NSModalResponse returnCode))handler NS_AVAILABLE_MAC(10_9);
#endif
- (IBAction)userButtonPressed:(id)sender {
UserLoginWindowController * wc = [UserLoginWindowController new];
// we keep a reference, so the WC doesn't deallocate
self.modalWindowController = wc;
[[self window] beginSheet:[wc window] completionHandler:^(NSModalResponse returnCode) {
self.modalWindowController = nil;
}];
}
in the UserLoginWindowController
- (IBAction)cancelButtonPressed:(id)sender {
[[[self window] sheetParent] endSheet:[self window] returnCode:NSModalResponseCancel];
}
- (IBAction)showSheet:(id)sender
{
if (_windowController == nil)
{
_windowController = [MyWindowController new];
}
[[self window] beginSheet:[_windowController window] completionHandler:^(NSModalResponse returnCode)
{
}];
}
// And inside your MyWindowController class:
- (id)init
{
self = [super initWithWindowNibName:#"MyWindowNibName"]; // TODO: Change the name of your NIB
return self;
}
In your nib file, make sure the "Visible At Launch" flag is unticked for the window.
I figured out how to do this. Hope it's ok to post..
MainWindow.h
#interface MainWindowController : NSWindowController {
NSString *sheetName;
IBOutlet NSWindow *sheet;
id result1;
id result2;
...
id resultn;
}
#property (strong) NSString *sheetName;
#property (strong, nonatomic) IBOutlet NSWindow *sheet;
-(IBAction)callSheet0:(id)sender;
-(IBAction)callSheet1:(id)sender;
-(IBAction)callSheetn:(id)sender;
- (void)openSheet;
- (IBAction)save:(id)sender;
- (IBAction)cancel:(id)sender;
MainWindow.m
- (void)windowDidLoad
{
NSLog(#"%s", __FUNCTION__);
[super windowDidLoad];
sheetName = [[NSString alloc] init];
}
-(IBAction)callSheet0:(id)sender {
NSLog(#"%s", __FUNCTION__);
sheetName = #"Sheet0";
[self openSheet];
}
....
-(IBAction)callSheetn:(id)sender {
NSLog(#"%s", __FUNCTION__);
sheetName = #"Sheetn";
[self openSheet];
- (void)openSheet {
NSLog(#"%s", __FUNCTION__);
NSLog(#"sheetName: %#",sheetName );
[[NSBundle mainBundle] loadNibNamed:sheetName owner:self topLevelObjects:nil];
[self.window beginSheet:self.sheet completionHandler:nil];
}
- (void)save:(NSButton*)sender {
switch ([sender tag]) {
case 0:
[self doSave1];
result = #"1";
break;
case 1:
[self doSave2];
result = #"2";
break;
case n:
[self doSaven];
result = #"x";
break;
}
[self endSheet:self.sheet returnCode:result];
}
- (IBAction)cancel:(id)sender {
NSLog(#"%s", __FUNCTION__);
result = #"0";
[self endSheet:self.sheet returnCode:result];
// returnCode is optional
}
//endSheet:(NSWindow *)sheetWindow {
- (void)endSheet:(NSWindow *)sheetWindow returnCode:returnCode {
//NSLog(#"%s", __FUNCTION__);
[sheetWindow orderOut:self];
}
- (void)save:(NSButton*)sender {
switch ([sender tag]) {
case 0:
[self doSave1];
result = #"1";
break;
case n:
[self doSave3];
result = #"3";
break;
}
[self endSheet:self.sheet returnCode:result];
}
With this method, new in 10.9,I don't need a special sheet controller, and control remains quote local.
I have a form-like view in my application which contains 8 textfields. Two of them are to be filled in by pickers, and the rest by normal heyboard typing. When picker-row is selected or when return button is pressed, the corresponding text should be entered into the textfield.
Could you please give some advice how to implement this properly? Also so that pickers/keyboards are dismissed after selection made/return pressed.
I found an answer to something similar here. ANd I managed to get the 2 picker-textfields working, but now I cannot make the keyboard appear for the rest. I guess it's because I'm overriding the textFieldShouldBegineEditing method. Any ideas to get round that? Can I somehow call the default method from inside textFieldShouldBeginEditing?? Note, if I uncomment my last lines of textFieldShouldBeginEditing I get a crash...
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
currentTextField = textField;
if (textField == self.pickerField1) {
currentArray = self.array1;
[pickerView reloadAllComponents];
pickerView.hidden = NO;
[self animatePickerViewIn];
return NO;
}
if (textField == self.pickerField2){
currentArray = self.array2;
[pickerView reloadAllComponents];
pickerView.hidden = NO;
[self animatePickerViewIn];
return NO;
}
// else {
// [currentTextField becomeFirstResponder];
// return NO;
// }
- (void)pickerView:(UIPickerView *)pickerView
didSelectRow:(NSInteger)row inComponent: (NSInteger)component
{
[currentTextField setText:[currentArray objectAtIndex:row]];
[currentTextField resignFirstResponder];
pickerView.hidden = YES;
}
Thanks!
Adding this for anyone that needs more information - here's how I got it work using user2135738's provided code:
MyViewController.h
#import <UIKit/UIKit.h>
#interface MyViewController : UIViewController <UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate>
#property (weak, nonatomic) IBOutlet UITextField *aTextField;
#property (weak, nonatomic) IBOutlet UITextField *bTextField;
#end
MyViewController.m
#import "MyViewController.h"
#interface MyViewController ()
#end
#implementation MyViewController {
NSArray *aArray,
*bArray,
*currentArray;
UITextField *currentTextField;
UIPickerView *pickerView;
}
- (void)viewDidLoad {
aArray = [NSArray arrayWithObjects: #1, #2, #3, #4, #5, #6, #7, #8, #9, #10, #11, #12, #13, #14, #15, #16, #17, #18, #19, #20, nil];
bArray = [NSArray arrayWithObjects:#"aString", #"bString", nil];
[super viewDidLoad];
pickerView = [[UIPickerView alloc] init];
pickerView.dataSource = self;
pickerView.delegate = self;
self.aTextField.delegate = self;
self.bTextField.delegate = self;
self.aTextField.inputView = pickerView;
self.bTextField.inputView = pickerView;
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
currentTextField = textField;
if (textField == self.aTextField) {
currentArray = aArray;
[pickerView reloadAllComponents];
pickerView.hidden = NO;
return YES;
} else if (textField == self.bTextField){
currentArray = bArray;
[pickerView reloadAllComponents];
pickerView.hidden = NO;
return YES;
} else {
[currentTextField becomeFirstResponder];
return NO;
}
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
return [currentArray count];
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
return [NSString stringWithFormat:#"%#",[currentArray objectAtIndex:row]];
}
#end
I have a problem in getting a method to work, and I am totally confused.
I am unable to hand over a string as a variable for my method.
I call the function even with the string, no variable currently.
Engine *myEngine = [Engine sharedInstance];
[myEngine getContentArrayFromEngine:#"zumbra"];
My method
-(NSMutableArray*) getContentArrayFromEngine:(NSString *)catName{
NSMutableSet* categorieContent = [[NSMutableSet alloc] init];
NSLog(#"Catname:%#", catName);
//some more code
}
NSLOG output
2011-12-18 18:49:44.165 Zitate[77224:15203] Catname:(null)
Why is catName empty ???
edit1: the complete code
ThirdViewController.m
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSString* myTempCatname;
myTempCatname = cell.textLabel.text;
// NSLog(#"test select %#", myTempCatname);
DetailViewController *detailVC = [self.storyboard instantiateViewControllerWithIdentifier:#"detailzitat"];
[self.navigationController pushViewController:detailVC animated:YES];
Engine *myEngine = [Engine sharedInstance];
[myEngine getContentArrayFromEngine:myTempCatname];
}
and in the engine.m
-(NSMutableArray*) getContentArrayFromEngine:(NSString *)catName{
NSMutableSet* categorieContent = [[NSMutableSet alloc] init];
NSLog(#"Übergebener Catname:%#", catName);
// catName=#"zumbra";
// NSLog(#"Inhalt InhalteFromWeb:%#", InhalteFromWeb);
NSLog(#"Catname:%#", catName);
unsigned count = [InhalteFromWeb count];
while (count--) {
NSLog(#"count %d %#", count, [[InhalteFromWeb objectAtIndex:count] objectForKey:CATEGORY]);
if([[[InhalteFromWeb objectAtIndex:count] objectForKey:CATEGORY] isEqualToString:catName]) {
[categorieContent addObject:[InhalteFromWeb objectAtIndex:count]];
NSLog(#"Row %d has Content%#",count, [InhalteFromWeb objectAtIndex:count]);
}
}
NSLog(#"Inhalt Category:%#", categorieContent);
NSArray* tempAr = [[NSArray alloc] initWithArray:[categorieContent allObjects]];
return [NSMutableArray arrayWithArray:tempAr];
}
EDIT2:
Ok, even the hint with the catName did not work. so I have changed my code a little bit.
I have an array with a category, title, content, author, image for each row
I would like to do two things
1) get a unique list of all categories (its working fine)
2) when tapping on one of these categories , open a detailView , show the first element of this category, jump to previous and next item in category by swiping around.
For this, I am going to SET the category I have chosen
First try was to handover in the method, which did not work.
Now I though, SET the category in my engine.h and when displaying the single item, get the array for this category back.
but again, the value of the category is not stored.
ThirdViewController.h
#import <UIKit/UIKit.h>
#import "SecondViewController.h"
#interface ThirdViewController : UIViewController<UITableViewDelegate, UITableViewDataSource> {
NSMutableArray* CategoryList;
}
#property (nonatomic, retain) NSMutableArray* CategoryList;
#end
ThirdViewController.m
#import "ThirdViewController.h"
#import "engine.h"
#import "DetailViewController.h"
#implementation ThirdViewController
#synthesize CategoryList;
- (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];
Engine *myEngine = [Engine sharedInstance];
CategoryList = [myEngine getCategories];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [CategoryList count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier =#"Cell";
UITableViewCell *cell = (UITableViewCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [CategoryList objectAtIndex:indexPath.row];
return cell;
}
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSString* myTempCatname;
myTempCatname = cell.textLabel.text;
DetailViewController *detailVC = [self.storyboard instantiateViewControllerWithIdentifier:#"detailzitat"];
[self.navigationController pushViewController:detailVC animated:YES];
Engine *myEngine = [Engine sharedInstance];
[myEngine setCategName:myTempCatname];
NSLog(#"Aufruf %#", myTempCatname);
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
DetailViewController.h
#import <UIKit/UIKit.h>
#import <MessageUI/MFMailComposeViewController.h>
#import "engine.h"
#interface DetailViewController : UIViewController<MFMailComposeViewControllerDelegate> {
IBOutlet UILabel *authorLabel;
IBOutlet UILabel *categoryLabel;
IBOutlet UILabel *titleLabel;
IBOutlet UITextView *contentTextView;
NSString *authorText, *contentText, *categoryText, *titleText, *imageText, *catName;
NSMutableArray *contentArray;
}
#property (nonatomic, retain) IBOutlet UITextView *contentTextView;
#property (nonatomic, retain) IBOutlet UILabel *authorLabel;
#property (nonatomic, retain) IBOutlet UILabel *categoryLabel;
#property (nonatomic, retain) IBOutlet UILabel *titleLabel;
#property (nonatomic, retain) NSString *authorText, *contentText, *categoryText, *titleText, *imageText, *catName;
#property (nonatomic, retain) NSMutableArray *contentArray;
-(IBAction)vorher:(id)sender;
-(IBAction)nachher:(id)sender;
#end
DetailViewController.m
#import "DetailViewController.h"
#implementation DetailViewController
#synthesize contentTextView;
#synthesize authorText, contentText, categoryText, titleText, imageText;
#synthesize authorLabel, categoryLabel, titleLabel;
#synthesize contentArray;
#synthesize catName;
int contentIndex;
int contentMax;
- (IBAction)swipeDetected:(UIGestureRecognizer *)sender {
NSLog(#"Right Swipe detected");
}
-(IBAction) vorher:(id)sender {
NSLog(#"-----VORHER Button gedrückt-------");
if (contentIndex==0) {contentIndex=contentMax-1;}
else {contentIndex--;}
titleText = [[contentArray objectAtIndex:contentIndex] objectForKey:TITLE];
authorText= [[contentArray objectAtIndex:contentIndex] objectForKey:AUTHOR];
contentText= [[contentArray objectAtIndex:contentIndex] objectForKey:CONTENT];
authorLabel.text=authorText;
titleLabel.text=titleText;
contentTextView.text=contentText;
}
-(IBAction) nachher:(id)sender {
NSLog(#"-----Nachher Button gedrückt-------");
if (contentIndex==contentMax-1) {contentIndex=0;}
else {contentIndex++;}
titleText = [[contentArray objectAtIndex:contentIndex] objectForKey:TITLE];
authorText= [[contentArray objectAtIndex:contentIndex] objectForKey:AUTHOR];
contentText= [[contentArray objectAtIndex:contentIndex] objectForKey:CONTENT];
authorLabel.text=authorText;
titleLabel.text=titleText;
contentTextView.text=contentText;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
Engine *myEngine = [Engine sharedInstance];
contentArray = [myEngine getContentArrayFromEngine];
contentMax = [contentArray count];
UISwipeGestureRecognizer *swipeRecognizerRight =
[[UISwipeGestureRecognizer alloc]
initWithTarget:self
action:#selector(vorher:)];
swipeRecognizerRight.direction = UISwipeGestureRecognizerDirectionRight;
[self.view addGestureRecognizer:swipeRecognizerRight];
UISwipeGestureRecognizer *swipeRecognizerLeft =
[[UISwipeGestureRecognizer alloc]
initWithTarget:self
action:#selector(nachher:)];
swipeRecognizerLeft.direction = UISwipeGestureRecognizerDirectionLeft;
[self.view addGestureRecognizer:swipeRecognizerLeft];
titleText = [[contentArray objectAtIndex:contentIndex] objectForKey:TITLE];
authorText= [[contentArray objectAtIndex:contentIndex] objectForKey:AUTHOR];
contentText= [[contentArray objectAtIndex:contentIndex] objectForKey:CONTENT];
authorLabel.text=authorText;
titleLabel.text=titleText;
contentTextView.text=contentText;
}
- (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);
}
#end
engine.h
//#import
#define AUTHOR #"author"
#define CATEGORY #"cat"
#define CONTENT #"content"
#define IMAGE #"image"
#define TITLE #"title"
#interface Engine : NSObject {
NSMutableArray* InhalteFromWeb;
NSInteger maxAnzahlInhalte;
NSString* categNameStorage;
}
+ (Engine *) sharedInstance;
- (NSMutableArray*) getZitateArrayFromEngine;
- (NSInteger) getMaxAnzahlZitateFromEngine;
- (NSString*) getAutor:(NSInteger)pos;
- (NSString*) getZitat:(NSInteger)pos;
- (NSString*) getAuthor:(NSInteger)pos;
- (NSString*) getCategory:(NSInteger)pos;
- (NSString*) getContent:(NSInteger)pos;
- (NSString*) getImage:(NSInteger)pos;
- (NSString*) getTitle:(NSInteger)pos;
-(NSMutableArray*) getContentArrayFromEngine;
-(void) setCategName:(NSString *) categNameVariable;
-(NSString*) getCategName;
-(NSMutableArray*) getCategories;
#end
engine.m
#import "Engine.h"
#implementation Engine
static Engine *_sharedInstance;
- (id) init
{
if (self = [super init])
{
// custom initialization
//Beginn my code
NSURL *url = [NSURL URLWithString:#"http://www.*/iMotivate.plist"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection )
{
InhalteFromWeb = [[NSMutableArray alloc] initWithContentsOfURL:url];
maxAnzahlInhalte = [InhalteFromWeb count];
}
else
{
NSLog(#"Connection failed");
}
}
return self;
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// NSLog(#"Recieving Response...");
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// NSLog(#"Recieving Data...");
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message : #"An error has occured.Please verify your internet connection."
delegate:nil
cancelButtonTitle :#"OK"
otherButtonTitles :nil];
[alert show];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// NSLog(#"DONE. Received Quotes: %d", maxAnzahlZitate);
}
// ###########
+ (Engine *) sharedInstance
{
if (!_sharedInstance)
{
_sharedInstance = [[Engine alloc] init];
}
return _sharedInstance;
}
// Getter and Setter for WebArray
- (NSMutableArray*) getZitateArrayFromEngine{
return InhalteFromWeb;
}
- (NSInteger) getMaxAnzahlZitateFromEngine{
return maxAnzahlInhalte;
}
- (NSString*) getAutor:(NSInteger)pos{
return [[InhalteFromWeb objectAtIndex:pos] objectForKey:AUTHOR];
}
- (NSString*) getZitat:(NSInteger)pos{
return [[InhalteFromWeb objectAtIndex:pos] objectForKey:CONTENT];
}
// #######
- (NSString*) getAuthor:(NSInteger)pos{
return [[InhalteFromWeb objectAtIndex:pos] objectForKey:AUTHOR];
}
- (NSString*) getCategory:(NSInteger)pos{
return [[InhalteFromWeb objectAtIndex:pos] objectForKey:CATEGORY];
}
- (NSString*) getContent:(NSInteger)pos{
return [[InhalteFromWeb objectAtIndex:pos] objectForKey:CONTENT];
}
- (NSString*) getImage:(NSInteger)pos{
return [[InhalteFromWeb objectAtIndex:pos] objectForKey:IMAGE];
}
- (NSString*) getTitle:(NSInteger)pos{
return [[InhalteFromWeb objectAtIndex:pos] objectForKey:TITLE];
}
-(NSArray*) getCategories {
NSMutableSet* categorieSet = [[NSMutableSet alloc] init];
unsigned count = [InhalteFromWeb count];
while (count--) {
NSString *tempString;
tempString=[[InhalteFromWeb objectAtIndex:count] objectForKey:CATEGORY];
// NSLog(#"tempString %#", tempString );
[categorieSet addObject:tempString];
}
// NSLog(#"categories from engine %#", categorieSet);
NSArray* tempAr = [[[NSArray alloc] initWithArray:[categorieSet allObjects]]sortedArrayUsingSelector:#selector(caseInsensitiveCompare:)];
return [NSMutableArray arrayWithArray:tempAr];
}
-(void) setCategName:(NSString *) categNameVariable
{ NSLog(#"categNameStorage 2%#",categNameStorage);
categNameStorage=categNameVariable;
NSLog(#"setCategName 1 %#",categNameVariable);
NSLog(#"categNameStorage 2%#",categNameStorage);
}
-(NSString*) getCategName {
return categNameStorage;
}
-(NSMutableArray*) getContentArrayFromEngine{
NSMutableSet* categorieContent = [[NSMutableSet alloc] init];
NSLog(#"Übergebener Catname:%#", categNameStorage);
// NSLog(#"Inhalt InhalteFromWeb:%#", InhalteFromWeb);
unsigned count = [InhalteFromWeb count];
while (count--) {
// NSLog(#"count %d %#", count, [[InhalteFromWeb objectAtIndex:count] objectForKey:CATEGORY]);
if([[[InhalteFromWeb objectAtIndex:count] objectForKey:CATEGORY] isEqualToString:categNameStorage]) {
[categorieContent addObject:[InhalteFromWeb objectAtIndex:count]];
// NSLog(#"Row %d has Content%#",count, [InhalteFromWeb objectAtIndex:count]);
}
}
// NSLog(#"Inhalt Category:%#", categorieContent);
NSArray* tempAr = [[NSArray alloc] initWithArray:[categorieContent allObjects]];
return [NSMutableArray arrayWithArray:tempAr];
}
#end
There has to be a variable conflict with 'catName' in your view controller. I'm not sure why the view controller would be in scope, but I bet if you change your parameter to "inCatName" it will be fine. It's good to use naming conventions like that for this reason.