Parent child navigation UIViewController causes exception for editing form - ios

I have a parent->child navigation setup in application. I use navigation via pushViewController function.
-(void)loadMemosViewController:(id)sender{
if(activeHullGuid != nil && activeHullGuid.length > 0)
{
NSString *storyboardName = #"MainStoryboard_iPhone1";
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle:nil];
MemosViewController *loginVC = [storyboard instantiateViewControllerWithIdentifier:#"sid_Memos"];
loginVC.keyReference = [[KeyValuePairIS alloc] initWithData:&controllerID:activeHullGuid];
[self.navigationController pushViewController:loginVC animated:YES];
}
}
for back navigation I use only default implementation in IOS (that would be a click on a back button).
This setup works for most situations, but recent implementation is causing problems.
The problem is this:
I have parent view controller named "hullViewController" and a child "memosViewController". The navigation between them works. Child does not report any information back to parent. HullViewController is also an editable form, which changes edit state via button in navigation bar.
Now if I change this edit/read state on hullViewController works nonstop. If I visit the child memosViewController, and go back to parent, I can only change state once more, then application crashes with exc_bad_access code=1.
After profiling with "Zombies" I found the culprit for exception is my probably disposed child memosViewController.
An Objective-C message was sent to a deallocated 'MemosViewController' object (zombie) at address: 0xdd52f10
it seams to crash on an IOS internal event, since none of my breakpoints are hit before crash.
A you can see the child is instanced during creation and I don't reference it to nothing else. Why would the edit state change request the child object?
What I tried already:
-declaring MemosViewController as a class variable. (application did not crash anymore, but would not change state anymore).
-initialising MemosViewController on viewDidLoad, changed nothing.
-calling child with class init only (not via storyboard), loaded child without UI, but result was same.
Project is set up with ARC, so I have minimum control on disposal of objects.
I have been searching for a solution quite a while now, with no results. Any help to solve my error editing if I visit the child would be appreciated.
UPDATE
I have additionally discovered, that when I get back to parent from child, the reference self.navigationItem still points to child, and any update to navigation buttons crashes the app.
**attaching custom ViewController, since it could be related to problem **
#import "UITableViewControllerEx.h"
#import "UITextFieldEx.h"
#import "UITextViewEx.h"
#import "GlobalValues.h"
#import "UITableViewEx.h"
#interface UITableViewControllerEx ()
#end
#implementation UITableViewControllerEx
UIBarButtonItem *bbi_navigateToMaster;
UIBarButtonItem *editButton;
UIButton *cmdEdit;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
[self setNavigationBackground];
[self setApplicationTintColor];
[self setApplicationTitleFont];
[self setupLeftBarButtonItem];
[self setBackButton];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//UITextFieldEx delegate to control the length of fields
- (BOOL)textField:(UITextFieldEx *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > textField.maxLength) ? NO : YES;
}
//UITextViewEx delegate to control the length of fields
-(BOOL)textView:(UITextViewEx *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
NSUInteger newLength = [textView.text length] + [text length] - range.length;
return (newLength > textView.maxLength) ? NO : YES;
}
//function to set left button to always pop to root controller
- (void)setBackButtonToReturnToMaster {
UIButton *cmdHome = [[UIButton alloc] initWithFrame:CGRectMake(0,0,30,30)];
[cmdHome setImage:[UIImage imageNamed:#"home"] forState:UIControlStateNormal];
bbi_navigateToMaster = [[UIBarButtonItem alloc] initWithCustomView:cmdHome];
[cmdHome addTarget:self action:#selector(backToMaster:) forControlEvents:UIControlEventTouchUpInside ];
self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:bbi_navigateToMaster , nil];
/*
bbi_navigateToMaster = [[UIBarButtonItem alloc] initWithTitle:#"" style:UIBarButtonItemStylePlain target:self action:#selector(backToMaster:)];
self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:bbi_navigateToMaster , nil];
[bbi_navigateToMaster setImage:[UIImage imageNamed:#"home"]];
[bbi_navigateToMaster setImageInsets:UIEdgeInsetsMake(2, 2, 2, 2)];*/
}
//pop to root controller
-(void)backToMaster:(id)sender {
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
}
else { [self.navigationController popToRootViewControllerAnimated:YES]; }
}
//find superview element of given type
- (UIView *)findSuperViewWithClass:(Class)superViewClass uiViewToSearch:(UIView*)bottomView{
UIView *superView = bottomView.superview;
UIView *foundSuperView = nil;
while (nil != superView && nil == foundSuperView) {
if ([superView isKindOfClass:superViewClass]) {
foundSuperView = superView;
break;
} else {
superView = superView.superview;
}
}
return foundSuperView;
}
-(void)setNavigationBackground{
if ([self.navigationController.navigationBar respondsToSelector:#selector(setBackgroundImage:forBarMetrics:)] ) {
UIImage *image = [UIImage imageNamed:#"navigationBackground"];
[self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
UIView* uv = [[UIView alloc] initWithFrame:CGRectMake(0, self.navigationController.navigationBar.frame.size.height-1,self.navigationController.navigationBar.frame.size.width, 1)];
[uv setBackgroundColor:[GlobalValues getTintColor]];
[self.navigationController.navigationBar insertSubview:uv atIndex:10];
}
}
//sets the tint color of szstem items (title, szstem buttons, ...)
-(void)setApplicationTintColor {
NSArray *ver = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:#"."];
if ([[ver objectAtIndex:0] intValue] >= 7) {
self.navigationController.navigationBar.barTintColor = [GlobalValues getTintColor];
self.navigationController.navigationBar.tintColor = [GlobalValues getTintColor];
self.navigationController.navigationBar.translucent = NO;
[self.navigationController.navigationBar setTitleTextAttributes:#{NSForegroundColorAttributeName : [UIColor whiteColor]}];
UIColor *color = [GlobalValues getTintColor];
self.view.tintColor = color;
}else {
//self.navigationController.navigationBar.tintColor = [GlobalValues getTintColor];
/*NSDictionary *textTitleOptions = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], UITextAttributeTextColor, [UIColor clearColor], UITextAttributeTextShadowColor, nil];
[[UINavigationBar appearance] setTitleTextAttributes:textTitleOptions];*/
}
}
//sets the navigation title
-(void)setApplicationTitleFont {
NSArray *ver = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:#"."];
if ([[ver objectAtIndex:0] intValue] >= 7) {
[self.navigationController.navigationBar setTitleTextAttributes:
[NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:#"HelveticaNeue-Light" size:21],
NSFontAttributeName, [UIColor whiteColor], UITextAttributeTextColor, [UIColor clearColor], UITextAttributeTextShadowColor, nil]];
}else {
[self.navigationController.navigationBar setTitleTextAttributes: #{
UITextAttributeTextColor: [UIColor whiteColor],
UITextAttributeFont: [UIFont fontWithName:#"Helvetica-Light" size:21.0f]
}];
}
}
-(void)setupLeftBarButtonItem{
cmdEdit = [[UIButton alloc] initWithFrame:CGRectMake(0,0,30,30)];
[cmdEdit setImage:[UIImage imageNamed:#"locked"] forState:UIControlStateNormal];
editButton = [[UIBarButtonItem alloc] initWithCustomView:cmdEdit];
[cmdEdit addTarget:self action:#selector(setEditState) forControlEvents:UIControlEventTouchUpInside];
}
- (UIBarButtonItem *)leftBarButtonItem
{
if (self.tableView.editing) {
[cmdEdit setImage:[UIImage imageNamed:#"unlocked"] forState:UIControlStateNormal];
return editButton;
}
else {
[cmdEdit setImage:[UIImage imageNamed:#"locked"] forState:UIControlStateNormal];
return editButton;
}
}
-(void)updateEditButton{
if (self.tableView.editing) {
[cmdEdit setImage:[UIImage imageNamed:#"unlocked"] forState:UIControlStateNormal];
}
else {
[cmdEdit setImage:[UIImage imageNamed:#"locked"] forState:UIControlStateNormal];
}
}
-(void)setEditState{
if (!self.tableView.editing) {
[self setEditing:YES animated:YES];
} else {
[self setEditing:NO animated:YES];
}
[self updateEditButton];
}
}*/
-(void) setBackButton{
UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *backBtnImage = [UIImage imageNamed:#"back"] ;
[backBtn setBackgroundImage:backBtnImage forState:UIControlStateNormal];
[backBtn addTarget:self action:#selector(goback) forControlEvents:UIControlEventTouchUpInside];
backBtn.frame = CGRectMake(0, 0, 30, 30);
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithCustomView:backBtn] ;
self.navigationItem.leftBarButtonItem = backButton;
}
- (void)goback
{
[self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - Table view data source
#pragma mark - Table view delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 0;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
cell.backgroundView=[[UIView alloc] initWithFrame:CGRectZero];
cell.backgroundColor = [UIColor clearColor];
cell.layer.backgroundColor = [UIColor clearColor].CGColor;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *customTitleView = [ [UIView alloc] initWithFrame:CGRectMake(10, 0, 300, 44)];
UIView *customTitleLineView = [ [UIView alloc] initWithFrame:CGRectMake(10, 43, self.view.frame.size.width -20, 0.5f)];
customTitleLineView.backgroundColor = [GlobalValues getTintColor];
UILabel *titleLabel = [ [UILabel alloc] initWithFrame:CGRectMake(20, 0, 300, 44)];
titleLabel.text = [self tableView:tableView titleForHeaderInSection:section];
titleLabel.font = [UIFont fontWithName:#"HelveticaNeue" size:18];
titleLabel.textColor = [GlobalValues getTintColor];
titleLabel.backgroundColor = [UIColor clearColor];
if (titleLabel.text.length != 0) {
[customTitleView addSubview:customTitleLineView];
}
[customTitleView addSubview:titleLabel];
return customTitleView;
}
#end

Seems I have found a solution to my problem.
Class UITableViewControllerEx contains functionality to setup edit button. The class variable "UIBarButtonItem *editButton;" is then used as edit button on all forms that inherit from "UITableViewControllerEx"
the solution was to instantiate UIBarButtonItem on each form inheriting UITableViewControllerEx with local name (like editButtonHull) and given as param to logic of superclass.
Thanks to #akashg for suggestion that Navigation bar modification might be the problem

Related

Switching from UIScreenEdgePanGestureRecognizer to UISegmentedControl in Objective-C

I am a new objective-c developer. The purpose of the app being developed is to switch between 3 graphs each displaying scientific data. When the user drags their finger on these graphs, the data for that point is displayed. Currently, to switch between these three graphs, the UIScreenEdgePanGestureRecognizer was used. However, since Apple has got rid of this feature in recent updates, I want to use segmented controls to switch between the three graphs. I have been able to get the segmented controls to appear, however, I have not been able to get them to actually get the graphs to switch. I have attached the relavant parts of the (ORIGINAL) viewcontroller.m below. How would I go about this? Thanks.
For reference, the names of the three graphs are ts, ph, and pv.
- (void)viewDidLoad
{
[super viewDidLoad];
/*
// Show/hide nav bar
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self
action:#selector(doubleTap)];
[tap setNumberOfTapsRequired:2];
[self.view addGestureRecognizer:tap];
*/
touchHasRegistered = NO;
allowQualityScrubbing = NO;
shouldFineTune = 0;
hasFineTuned = NO;
[[UIApplication sharedApplication] setStatusBarHidden:YES];
[self.navigationController setNavigationBarHidden:YES];
[self.containerView addSubview:self.chartView];
[self.view insertSubview:self.secondContainerView
aboveSubview:self.containerView];
[self.view insertSubview:self.infoView
aboveSubview:self.secondContainerView];
[self.containerView bringSubviewToFront:self.infoButton];
[self.view setBackgroundColor:[UIColor whiteColor]];
[self.chartView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.containerView);
}];
[self.infoView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.containerView);
}];
if (self.secondContainerView.superview != nil && self.chartView.image != nil) {
[self.secondContainerView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.containerView).with.offset(20.0);
make.top.equalTo(self.containerView).with.offset(20.0);
make.height.equalTo([NSNumber numberWithFloat:self.secondContainerView.frame.size.height]);
make.width.equalTo([NSNumber numberWithFloat:self.secondContainerView.frame.size.width]);
}];
}
[self.secondContainerView addSubview:self.displayView];
[self chooseNewFileWithChartType:self.chartView.chart.substanceType valueType:#"ts"];
UIScreenEdgePanGestureRecognizer *rightRecog = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self
action:#selector(resetChart:)];
[rightRecog setEdges:UIRectEdgeRight];
[rightRecog setCancelsTouchesInView:YES];
[self.chartView addGestureRecognizer:rightRecog];
UIScreenEdgePanGestureRecognizer *leftRecog = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self
action:#selector(resetChart:)];
[leftRecog setEdges:UIRectEdgeLeft];
[leftRecog setCancelsTouchesInView:YES];
[self.chartView addGestureRecognizer:leftRecog];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self.view addSubview:self.popupView];
[self.popupView mas_makeConstraints:^(MASConstraintMaker *make) {
make.height.equalTo(#(self.popupView.frame.size.height));
make.width.equalTo(#(self.popupView.frame.size.width));
make.center.equalTo(self.view);
}];
/*
// Add Adjuster Views
NSSet *tags = [self tagsForAdjusterViews];
CGFloat height = self.displayView.containerViewHeight/self.displayView.numberOfRows;
for (id tag in tags) {
RUAAdjusterView *adjusterView = [[RUAAdjusterView alloc] initWithFrame:CGRectZero
tag:[(NSNumber *)tag integerValue]];
adjusterView.delegate = self;
[adjusterView setBackgroundColor:[UIColor clearColor]];
[self.secondContainerView addSubview:adjusterView];
[self.secondContainerView bringSubviewToFront:adjusterView];
[adjusterView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.secondContainerView);
make.right.equalTo(self.secondContainerView);
make.top.equalTo([NSNumber numberWithFloat:(height*([(NSNumber *)tag floatValue] - 1) + self.displayView.containerViewOriginY + 2.0f)]);
make.height.equalTo([NSNumber numberWithFloat:height - 4.0f]);
}];
}
*/
}
- (NSSet *)tagsForAdjusterViews
{
return [NSSet setWithObjects:#1, #2, #6, #7, nil];
}
- (BOOL)prefersStatusBarHidden
{
return YES;
}
#pragma mark - Lazy Init
- (LocationIndicatorImageView *)chartView
{
if (!_chartView) {
_chartView = (LocationIndicatorImageView *)[[LocationIndicatorImageView alloc] initWithFrame:self.containerView.frame
image:[UIImage imageNamed:#"Water_ts_chart.png"]
sender:self];
[_chartView setChart:[RUChart chartWithChartType:#"ts"]];
}
return _chartView;
}
-(UIView *)displayView
{
if (!_displayView) {
_displayView = [[DisplayView alloc] initWithFrame:self.secondContainerView.frame];
[_displayView setDataSource:self];
}
return _displayView;
}
-(UIView *)secondContainerView
{
if (!_secondContainerView) {
CGFloat height = 343.0f;
CGFloat width = 225.0f;
_secondContainerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, height)];
}
return _secondContainerView;
}
-(UIImageView *)infoView
{
if (!_infoView) {
_infoView = [[UIImageView alloc] initWithFrame:CGRectZero];
[_infoView setImage:[UIImage imageNamed:#"Legend.png"]];
[_infoView setHidden:YES];
[_infoView setUserInteractionEnabled:NO];
[_infoView setBackgroundColor:[UIColor whiteColor]];
UIView *container = [[UIView alloc] initWithFrame:CGRectMake(30, 30, 310, 310)];
UITapGestureRecognizer *ytTap = [[UITapGestureRecognizer alloc] initWithTarget:self
action:#selector(showYoutubeVideo)];
[ytTap setNumberOfTapsRequired:1];
[container setUserInteractionEnabled:YES];
[container addGestureRecognizer:ytTap];
[_infoView addSubview:container];
UIImageView *youtube = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
[youtube setImage:[UIImage imageNamed:#"youtube.png"]];
UITextView *textView1 = [[UITextView alloc] initWithFrame:CGRectMake(youtube.frame.origin.x + youtube.frame.size.width,
youtube.frame.origin.y,
250,
youtube.frame.size.height/2.0)];
UITextView *textView2 = [[UITextView alloc] initWithFrame:CGRectMake(youtube.frame.origin.x + youtube.frame.size.width,
youtube.frame.origin.y + youtube.frame.size.height/2.0,
250,
youtube.frame.size.height/2.0)];
UIFont *font = [UIFont fontWithName:#"HelveticaNeue-Light" size:16.0];
[textView1 setText:#"Learn about Thermodynamic"];
[textView1 setFont:font];
[textView1 setTextContainerInset:UIEdgeInsetsMake(11.0, 4.0, 4.0, 0.0)];
[textView1 setUserInteractionEnabled:NO];
[textView2 setText:#"Properties of Water"];
[textView2 setFont:font];
[textView2 setTextContainerInset:UIEdgeInsetsMake(0.0, 4.0, 0.0, 0.0)];
[textView2 setUserInteractionEnabled:NO];
[container addSubview:youtube];
[container addSubview:textView1];
[container addSubview:textView2];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self
action:#selector(dismissInfo)];
[tap setNumberOfTapsRequired:1];
[_infoView addGestureRecognizer:tap];
}
return _infoView;
}
- (void)showYoutubeVideo
{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"http://www.youtube.com/watch?v=rJR-6OEw09k"]
options:#{}
completionHandler:nil];
}
- (H2O_Wagner_Pruss *)wagPruss
{
if (!_wagPruss) {
_wagPruss = [[H2O_Wagner_Pruss alloc] initEOS];
}
return _wagPruss;
}
- (NSArray *)superheatedValues
{
if (!_superheatedValues) {
_superheatedValues = [[NSArray alloc] init];
}
return _superheatedValues;
}
- (NSArray *)superheatedKeys
{
if (!_superheatedKeys) {
_superheatedKeys = [[NSArray alloc] init];
}
return _superheatedKeys;
}
- (NSArray *)chartValueTypes
{
if (!_chartValueTypes) {
_chartValueTypes = [NSArray arrayWithObjects:#"ts",#"ph",#"pv", nil];
}
return _chartValueTypes;
}
- (RUAPopupView *)popupView
{
if (!_popupView) {
_popupView = [[RUAPopupView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 200.0f, 160.0f) text:#"t-s"];
}
return _popupView;
}
- (RUASpaceController *)spaceController
{
if (!_spaceController) {
_spaceController = [[RUASpaceController alloc] init];
// NOTE: Seems like (10/8.0 and 10/9.0) and 20/30.0 felt best of ones I tried. Could use some refining.
_spaceController.numPoints = 10;
_spaceController.maxDiff = 7.0;
}
return _spaceController;
}
#pragma mark - Gesture Selectors
- (IBAction)displayInfo:(id)sender {
[self.infoView setHidden:NO];
[self.infoView setUserInteractionEnabled:YES];
}
-(void)dismissInfo
{
[self.infoView setHidden:YES];
[self.infoView setUserInteractionEnabled:NO];
}
-(void)doubleTap
{
[self.popupView showHideAnimated:YES];
/*
if (self.navigationController.isNavigationBarHidden) {
[self.navigationController setNavigationBarHidden:NO animated:YES];
[[UIApplication sharedApplication] setStatusBarHidden:NO];
} else {
[self.navigationController setNavigationBarHidden:YES animated:YES];
[[UIApplication sharedApplication] setStatusBarHidden:YES];
}
*/
}
- (void)resetChart:(UIScreenEdgePanGestureRecognizer *)recog
{
[self.popupView.layer removeAllAnimations];
if (recog.state == UIGestureRecognizerStateEnded) {
NSInteger index = [self.chartValueTypes indexOfObject:self.chartView.chart.valueType];
NSLog(#"%#, %#", self.chartValueTypes[((index+1)+3)%3], self.chartValueTypes[((index-1)+3)%3]);
NSString *type;
if (recog.edges == UIRectEdgeRight) {
type = self.chartValueTypes[((index+1)+3)%3];
} else if (recog.edges == UIRectEdgeLeft) {
type = self.chartValueTypes[((index-1)+3)%3];
}
NSString *letter1 = [type substringToIndex:1];
NSString *letter2 = [type substringFromIndex:1];
NSString *displayName = [NSString stringWithFormat:#"%#-%#",letter1.uppercaseString,letter2];
self.popupView.text = displayName;
[self.chartView resetImage:[UIImage imageNamed:[NSString stringWithFormat:#"Water_%#_chart.png",type]]];
self.chartView.chart = [RUChart chartWithChartType:type];
[self inspectInfoButtonWithChartValueType:type];
[self chooseNewFileWithChartType:self.chartView.chart.substanceType valueType:type];
[self.secondContainerView mas_remakeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.containerView).with.offset(20.0);
make.height.equalTo([NSNumber numberWithFloat:self.secondContainerView.frame.size.height]);
make.width.equalTo([NSNumber numberWithFloat:self.secondContainerView.frame.size.width]);
}];
if (self.chartView.chart.displayPosition == RUChartDisplayPositionLeft) {
[self.secondContainerView mas_updateConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.containerView).with.offset(20.0);
}];
} else if (self.chartView.chart.displayPosition == RUChartDisplayPositionRight) {
[self.secondContainerView mas_updateConstraints:^(MASConstraintMaker *make) {
make.right.equalTo(self.containerView).with.offset(-20.0);
}];
}
[self.popupView showHideAnimated:YES];
if (touchHasRegistered) {
if ([self.chartView.chart.valueType isEqualToString:#"ph"]) {
if ([self.chartView pointIsWithinBoundsForPrimaryAxisValue:currentEnthalpy secondaryAxisValue:currentPressure]) {
[self.chartView moveMarkerToPrimaryAxisValue:currentEnthalpy
secondaryAxisValue:currentPressure];
} else {
[self.chartView removeMarker];
}
} else if ([self.chartView.chart.valueType isEqualToString:#"pv"]) {
if ([self.chartView pointIsWithinBoundsForPrimaryAxisValue:currentSpecVolume secondaryAxisValue:currentPressure]) {
[self.chartView moveMarkerToPrimaryAxisValue:currentSpecVolume
secondaryAxisValue:currentPressure];
} else {
[self.chartView removeMarker];
}
} else if ([self.chartView.chart.valueType isEqualToString:#"ts"]) {
if ([self.chartView pointIsWithinBoundsForPrimaryAxisValue:currentEntropy secondaryAxisValue:currentTemp]) {
[self.chartView moveMarkerToPrimaryAxisValue:currentEntropy
secondaryAxisValue:currentTemp];
} else {
[self.chartView removeMarker];
}
} else {
touchHasRegistered = NO;
[self.chartView removeMarker];
}
}
}
}
UISegmentedControl look like a lot to setup, but actually is not.
The following code just shows more detailed control in color and label positions inside the segments. If there is no further use somewhere else, there is no property needed to hold UISegmentedControl *. Call this once in -initWithFrame: or -viewDidLoad.
- (void)setupSegmentCtrl {
UISegmentedControl *segmentedCtrl = [[UISegmentedControl alloc] initWithItems:#[#"A",#"B",#"C"]];
segmentedCtrl.momentary = YES;
NSUInteger segItems = segmentedCtrl.numberOfSegments;
segmentedCtrl.frame = CGRectMake(0, 0, 60*segItems, 40);
// sorry - funny color scheme used to demonstrate
segmentedCtrl.tintColor = UIColor.orangeColor;
//segmentedCtrl.backgroundColor = UIColor.clearColor;
UIColor *dark = [UIColor colorWithWhite:0.5 alpha:0.5];
[segmentedCtrl setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:dark,NSForegroundColorAttributeName, [UIFont fontWithName:#"HelveticaNeue-Light" size:16.0],NSFontAttributeName, nil] forState:UIControlStateNormal];
[segmentedCtrl setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:UIColor.redColor, NSForegroundColorAttributeName, nil] forState:UIControlStateSelected];
[segmentedCtrl setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:UIColor.greenColor, NSForegroundColorAttributeName, nil] forState:UIControlStateHighlighted];
// you can move the segments labels about some pixels with the following..
//[segmentedCtrl setContentPositionAdjustment:UIOffsetMake(-1, -2) forSegmentType:UISegmentedControlSegmentAny barMetrics:UIBarMetricsDefault];
// manually set an active index, .. as default
[segmentedCtrl setSelectedSegmentIndex:0];
[self.view addSubview:segmentedCtrl];
// next lines work for all UIControls, setting a target and action manually.
// there are a lot UIControlEvent to choose/combine from available
[segmentedCtrl addTarget:self action:#selector(segmentSelectedAction:) forControlEvents:UIControlEventValueChanged];
}
and as defined you will want a method that takes action when you touch the segments.
-(void)segmentSelectedAction:(UISegmentedControl *)seg {
NSLog(#"selectedSegmentIndex=%d", seg.selectedSegmentIndex);
// what ever you gonna do with the seg.selectedSegmentIndex
}
and maybe good to know when using UISegmentedControl, when going in dark mode it has different color scheme for the background. So switch and test how it looks like.
If you have to change layout cause of device rotates, you will have to expose UISegmentedControl *segmentCtrl as property or class variable and change frame and so on in -layoutSubviews to your needs.
A last word to UIViews and UIGestureRecognizers. Sometime its much more practical to write your own UIView subclass and allocate that instead. Then you are able to use the following methods inside your subclass to catch touches directly.
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesBegan:touches withEvent:event];
for (UITouch *touch in touches) {
NSLog(#"touchesBegan= %#",touch.description);
}
}
// and the other possible..
-(void)touchesMoved:withEvent:
-(void)touchesEnded:withEvent:
-(void)touchesCancelled:withEvent:

UISwitch suddenly changed background color from clearColor to whiteColor

So I have a UISwitch that backgroundColor already set to clearColor in tableViewCell.m :
- (instancetype)initWithStyle:(UITableViewCellStyle)style
reuseIdentifier:(NSString *)reuseIdentifier
{
if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])
{
self.selectionStyle = UITableViewCellSelectionStyleNone;
self.backgroundColor = [UIColor colorWithHexString:#"#333333"];
[self initUI];
}
return self;
}
- (void)initUI {
[self addSubview:self.topLine];
[self addSubview:self.imgView];
[self addSubview:self.titleLab];
[self addSubview:self.rightView];
[self addSubview:self.rightSwitch];
[self addSubview:self.cellLine];
[self addSubview:self.bottomLine];
}
- (UISwitch *)rightSwitch {
if (!_rightSwitch) {
self.rightSwitch = [[UISwitch alloc] init];
self.rightSwitch.frame = CGRectMake(253*kScaleXAndWidth, 8*kScaleYAndHeight, 51*kScaleXAndWidth, 31*kScaleYAndHeight);
self.rightSwitch.hidden = YES;
[self.rightSwitch setBackgroundColor:[UIColor clearColor]];
[self.rightSwitch addTarget:self action:#selector(rightSwitchClick:) forControlEvents:UIControlEventTouchUpInside];
}
return _rightSwitch;
}
rightSwitchClick is a block, then in cellForRowAtIndexPath TableViewController.m :
QuickLoginCell *cell = [tableView dequeueReusableCellWithIdentifier:QuickLoginCellID forIndexPath:indexPath];
cell.rightView.hidden = YES;
cell.rightSwitch.hidden = NO;
__block QuickLoginCell *blockCell = cell;
if (isIDlogin) {
[cell.rightSwitch setEnabled:NO];
}
else{
[cell.rightSwitch setEnabled:YES];
}
cell.rightSwitch.on = NO;
cell.bottomLine.hidden = NO;
if (![BetwayUtils isEmptyString:patternLock]) {
cell.rightSwitch.on = YES;
cell.bottomLine.hidden = YES;
}
[cell.imgView setImage:[UIImage imageNamed:#"ic_patternLock"]];
cell.rightSwitchAddClick = ^{
if (blockCell.rightSwitch.on) {
PatternLockViewController *vc = [PatternLockViewController new];
[strongSelf.navigationController pushViewController:vc animated:YES];
}
else{
}
};
so when turn on it will directly go to PatternLockViewController, and after I have set the patternLock it will pop to TableViewController again and the switch will be turned on now. the problem is when I try to switch it off the backgroundColor suddenly change to white like this :
When I remove :
PatternLockViewController *vc = [PatternLockViewController new];
[strongSelf.navigationController pushViewController:vc animated:YES];
so inside the block there is no code and the UISwitch backgroundColor is clearColor, I tried to switch on and off and it works as it supposed to be. so i am a little bit confused on this matter since I dont set UISwitch backgroundColor to white anywhere.
UPDATE
Already tried using delegate to refresh table when pop from patternlockviewcontroller but still no avail
I solve it using :
- (void)prepareForReuse {
[super prepareForReuse];
[self.rightSwitch setBackgroundColor:[UIColor clearColor]];
[self.rightSwitch setTintColor:[UIColor whiteColor]];
[self.rightSwitch setThumbTintColor:[UIColor whiteColor]];
}
on my tableViewCell.m I hope it will help someone here.

iOS PageView help. Button actions vs. button creation

So I hired someone on freelancer to build me a pageview, and it looked like what I wanted, but now Idk how to configure the code. Can anyone just tell me where the buttons are being built and where the actions to each button are?
ViewController.m
- (ColorViewController *)viewControllerAtIndex:(NSUInteger)index {
if (([colorsArray count] == 0) || (index >= [colorsArray count])) {
return nil;
}
NSArray *arr = [colorsArray objectAtIndex:index];
ColorViewController *dataViewController =[[ColorViewController alloc] initWithColorsArray:arr];
dataViewController.delegate = self;
return dataViewController;
}
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(ColorViewController *)viewController
{
int index = [self indexOfViewController:viewController];
pagecontrol.currentPage = index;
if(index == 0){
return nil;
}
return [self viewControllerAtIndex:index-1];
}
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(ColorViewController *)viewController
{
int index = [self indexOfViewController:viewController];
pagecontrol.currentPage = index;
if(index >= [colorsArray count]-1){
return nil;
}
return [self viewControllerAtIndex:index+1];
}
- (NSUInteger)indexOfViewController:(ColorViewController *)viewController {
return [colorsArray indexOfObject:viewController.colorsArray];
}
-(void) pageChanged:(id) sender
{
}
-(void) setColor:(UIColor *)color
{
[myLabel setTextColor:color];
_fontColorView.hidden = YES;
}
-(void) setupColorViewControllers
{
NSDictionary *options =[NSDictionary dictionaryWithObject:[NSNumber numberWithInteger:UIPageViewControllerSpineLocationMin]
forKey: UIPageViewControllerOptionSpineLocationKey];
pagevc = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:options];
pagevc.view.frame = CGRectMake(0, 414, 320, 200);
pagevc.delegate = self;
pagevc.dataSource = self;
[self.view addSubview:pagevc.view];
NSArray *c1arr = [NSArray arrayWithObjects:[UIColor redColor],
[UIColor blackColor],
[UIColor grayColor],
[UIColor blueColor],
[UIColor redColor],
[UIColor darkGrayColor],
[UIColor yellowColor],
[UIColor purpleColor],
[UIColor greenColor],
nil];
ColorViewController *c1 = [[ColorViewController alloc] initWithColorsArray:c1arr];
c1.delegate = self;
NSArray *c2arr = [NSArray arrayWithObjects:[UIColor whiteColor],
[UIColor redColor],
[UIColor blackColor],
[UIColor grayColor],
[UIColor darkGrayColor],
[UIColor purpleColor],
[UIColor yellowColor],
[UIColor blueColor],
[UIColor greenColor],
nil];
NSArray *c3arr = [NSArray arrayWithObjects:
[UIColor greenColor],
[UIColor blackColor],
[UIColor darkGrayColor],
[UIColor grayColor],
[UIColor whiteColor],
[UIColor purpleColor],
[UIColor yellowColor],
[UIColor blueColor],
[UIColor redColor],
nil];
colorsArray = [NSArray arrayWithObjects:c1arr, c2arr, c3arr, nil];
colorsViewControllers = [NSArray arrayWithObjects:c1, nil];
pagecontrol = [[UIPageControl alloc] initWithFrame:CGRectMake(110, 150, 80, 30)];
pagecontrol.layer.cornerRadius = 4;
[pagecontrol setBackgroundColor:[UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:0.8]];
[pagecontrol setPageIndicatorTintColor:[UIColor purpleColor]];
pagecontrol.numberOfPages = 3;
pagecontrol.currentPage = 0;
[pagecontrol addTarget:self action:#selector(pageChanged:) forControlEvents:UIControlEventValueChanged];
[pagevc.view addSubview:pagecontrol];
[pagevc setViewControllers:colorsViewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:^(BOOL finished) {
;
}];
pagevc.view.hidden = YES;
_fontColorView = pagevc.view;
}
ColorViewController.m
#import "ColorViewController.h"
#interface ColorViewController ()
#end
#implementation ColorViewController
#synthesize colorsArray;
#synthesize delegate;
-(void) setColorsArray:(NSArray*) arr
{
colorsArray = arr;
int min = [arr count] > [buttonsArray count] ? [buttonsArray count] : [arr count];
for(int i = 0; i < min; i++){
UIColor *color = [colorsArray objectAtIndex:i];
UIButton *b = [buttonsArray objectAtIndex:i];
[b setBackgroundColor:color];
}
}
-(id) initWithColorsArray:(NSArray*) arr
{
self = [super init];
if(self){
colorsArray = arr;
}
return self;
}
-(void) color:(id) sender
{
UIButton *b = (UIButton*) sender;
[delegate setColor:b.backgroundColor];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
buttonsArray = [[NSMutableArray alloc] init];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
int x = 10, y = 10;
int size = [colorsArray count] > 10 ? 10 : [colorsArray count];
for(int i = 0; i < size; i++){
UIColor *color = [colorsArray objectAtIndex:i];
UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom];
[b setBackgroundColor:color];
[b addTarget:self action:#selector(color:) forControlEvents:UIControlEventTouchUpInside];
b.frame = CGRectMake(x , y , 50, 50);
x += 60;
if(i == 4){
y += 60;
x = 10;
}
[buttonsArray addObject:b];
[self.view addSubview:b];
}
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
#end
The buttons are being instantiated in ViewDidLoad within the ColorViewController class. A button is created for every color in colorsArray
for(int i = 0; i < size; i++){
UIColor *color = [colorsArray objectAtIndex:i];
UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom];
and then each of the buttons is given the selector "color:" for the touchUpInside event, meaning that when the button is pressed and released, it will call the method "color" within the same class.
[b addTarget:self action:#selector(color:) forControlEvents:UIControlEventTouchUpInside];
The "colors:" method checks which button was pressed and then sets the background color of the delegate class to the background color of the button
UIButton *b = (UIButton*) sender;
[delegate setColor:b.backgroundColor];

Determine if current screen has visible navigation bar

I have a singlton object. Is there any simple way to determine if current screen contains a navigation bar within singlton methods?
The singleton is UIView subclass. It's designed for showing prorgess activity, e.g. network exchange. It looks like black rectangle dropping down from top and hiding when the work is done. Why singleton? It's easy to call it from any place of code
The followed snippet is showing the initialization of activity singleton and published here just for better understaning my idea.
-(void) showUpdatingView:(NSString *) msg {
[self initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 44)];
activity = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite] autorelease];
activity.frame = CGRectMake(5, 10, 22, 22);
labelView = [[[UILabel alloc] initWithFrame:CGRectMake(35, 10, [UIScreen mainScreen].bounds.size.width - 10, 22)] autorelease];
labelView.font = [UIFont boldSystemFontOfSize:12];
labelView.backgroundColor = [UIColor clearColor];
labelView.textColor = [UIColor whiteColor];
labelView.text = msg;
[self addSubview:activity];
[self addSubview:labelView];
self.backgroundColor = [UIColor blackColor];
self.alpha = 0.7;
}
The activity can be called by
[[ActivitySingleton getInstance] showUpdatingView:#"Getting data."];
it's not all.
The singleton is being created in AppDelegate object and the view is added to
inlineActivity = [[CHInlineActivityView alloc] initView];
[self.window.rootViewController.view addSubview:inlineActivity];
I know it may look crazy. But when I was designing it seemed to me reasonable
if you have all in one navigationController:
BOOL navHidden = self.window.rootViewController.navigationController.navigatonBarHidden;
if you don't it is a bit harder.. you could check the window's subviews and see if you can find a UINavigationBar
id navbar = [self.window firstSubviewOfKind:[UINavigationBar class] withTag:NSNotFound];
BOOL navHidden = navbar == nil;
#implementation NSView (findSubview)
- (NSArray *)findSubviewsOfKind:(Class)kind withTag:(NSInteger)tag inView:(NSView*)v {
NSMutableArray *array = [NSMutableArray array];
if(kind==nil || [v isKindOfClass:kind]) {
if(tag==NSNotFound || v.tag==tag) {
[array addObject:v];
}
}
for (id subview in v.subviews) {
NSArray *vChild = [self findSubviewsOfKind:kind withTag:tag inView:subview];
[array addObjectsFromArray:vChild];
}
return array;
}
#pragma mark -
- (NSView *)firstSubviewOfKind:(Class)kind withTag:(NSInteger)tag {
NSArray *subviews = [self findSubviewsOfKind:kind withTag:tag inView:self];
return subviews.count ? subviews[0] : nil;
}
#end

toolbar previous and next button logic

I'm using the following code to move to the next field using the UITextField delegate and also I'm adding a toolbar to the keyboard with the previous, next and ok buttons. The code is working fine.
Like you see the keyboard return button logic is pretty generic, using the UITextField tags, and that's good because I'm gonna use the piece of code all around. Now I will need to write the previous and next buttons logic, and I'm lost. Any ideas?
UPDATE (complete code, with some modifications, thanks to #8vius that spent some time with me in the chat to make it work):
//
// SigninViewController.m
//
#import "SigninViewController.h"
#implementation SigninViewController
#synthesize firstResponder = _firstResponder;
#synthesize toolbar;
#synthesize email;
#synthesize password;
- (void)move:(UIBarButtonItem*)sender {
NSInteger tag = self.firstResponder.tag;
if ([sender.title isEqualToString:#"Anterior"]) {
tag -= 1;
} else if ([sender.title isEqualToString:#"Próximo"]) {
tag += 1;
}
UITextField *nextTextField = (UITextField*)[self.view viewWithTag:tag];
if (nextTextField && tag > 0) {
[nextTextField becomeFirstResponder];
} else {
[self.firstResponder resignFirstResponder];
self.firstResponder = nil;
}
}
- (void)ok:(id)sender {
[self.view endEditing:YES];
self.firstResponder = nil;
}
- (void)textFieldDidBeginEditing:(UITextField*)textField {
self.firstResponder = textField;
}
- (BOOL)textFieldShouldReturn:(UITextField*)textField {
NSInteger tag = textField.tag + 1;
UITextField *nextTextField = (UITextField*)[self.view viewWithTag:tag];
if (nextTextField) {
[nextTextField becomeFirstResponder];
} else {
[textField resignFirstResponder];
self.firstResponder = nil;
}
return NO;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.email.delegate = self;
self.password.delegate = self;
if (self.toolbar == nil)
{
self.toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 44)];
UIBarButtonItem* previous = [[UIBarButtonItem alloc] initWithTitle:#"Anterior" style:UIBarButtonItemStyleBordered target:self action:#selector(move:)];
UIBarButtonItem* next = [[UIBarButtonItem alloc] initWithTitle:#"Próximo" style:UIBarButtonItemStyleBordered target:self action:#selector(move:)];
UIBarButtonItem* space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemFlexibleSpace) target:nil action:nil];
UIBarButtonItem* ok = [[UIBarButtonItem alloc] initWithTitle:#"Ok" style:UIBarButtonItemStyleBordered target:self action:#selector(ok:)];
[self.toolbar setItems:[[NSArray alloc] initWithObjects:previous, next, space, ok, nil]];
[self.toolbar setTranslucent:YES];
[self.toolbar setTintColor:[UIColor blackColor]];
}
for (UIView* view in self.view.subviews) {
if ([view isKindOfClass:[UITextField class]]) {
[(UITextField*)view setInputAccessoryView:toolbar];
}
}
}
- (void)viewDidUnload {
self.email = nil;
self.password = nil;
[super viewDidUnload];
}
#end
It's quite simple, when you load your view you set the tag property on your text fields depending on the order you want them in, then you have to just traverse the tag element on the fields:
- (void)toggleTextfield:(UIBarButtonItem *)sender {
NSInteger nextTag = self.firstResponder.tag;
if ([sender.title isEqualToString:#"Previous"] && nextTag > 1) {
nextTag -= 1
} else if ([sender.title isEqualToString:#"Next"]) {
nextTag += 1;
}
UITextField *nextTextField = (UITextField *)[self.view viewWithTag:nextTag];
if (nextTextField) {
[nextTextField becomeFirstResponder];
}
}
And keep track of who is the first responder:
-(void)textFieldDidBeginEditing:(UITextField *)textField {
self.firstResponder = textField;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
self.firstResponder = nil;
return YES;
}
And when you load your view, you bind the buttons to the toggle action:
UIBarButtonItem *previousButton = [[UIBarButtonItem alloc] initWithTitle:#"Previous"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(toggleTextfield:)];
UIBarButtonItem *nextButton = [[UIBarButtonItem alloc] initWithTitle:#"Next"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(toggleTextfield:)];
In my case, for instance, I set up my text fields inside a table view, so in my cellForRowAtIndexPath method I set the tag property to be the row of the indexPath.
EDIT: You have to set the firstResponder property for it to work.
In your .h file:
#property UIView *firstResponder
In your .m file:
#synthesize firstResponder = _firstResponder;

Resources