Right bar button item not show without first time - ios

This is first time, edit button visible. But when i come from another tab edit button not visible, but if i press there it will visible. In my UITableView i use a rightBarButton Edit item in UINavigationBar. But it show's only first time. When I come from another tab to this tab next time, it's not shown. If i press in that place of that button it become shown. What is the problem?
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Edit" style:UIBarButtonItemStylePlain target:self action:#selector(editActionOfTable) ];
-(void)editActionOfTable{
if (isEdited) {
isSelctedAll = NO;
[self.selectallButton setTitle:#"Select All" forState:UIControlStateNormal];
self.navigationItem.rightBarButtonItem.title = #"Edit";
//[self.editButton setTitle:#"Edit" forState:UIControlStateNormal];
[self.tableView setEditing:NO animated:YES];
[self customViewHide:YES];
isEdited = NO;
isDeleteButtonPress = false;
self.navigationItem.hidesBackButton = NO;
flagForCustomCell = false;
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:#"bottom" forKey:#"pos_Key"];
[[NSNotificationCenter defaultCenter] postNotificationName: #"ad_banner" object:nil userInfo:userInfo];
}
else{
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:#"top_of_tab" forKey:#"pos_Key"];
[[NSNotificationCenter defaultCenter] postNotificationName: #"ad_banner" object:nil userInfo:userInfo];
flagForCustomCell = true;
//disable delete button when array empty
[self.deleteButtonOutlet setEnabled:NO];
self.deleteButtonOutlet.alpha = 0.5;
//disable fav button when array empty
[self.favInHistoryOutlet setEnabled:NO];
self.favInHistoryOutlet.alpha = 0.5;
self.navigationItem.rightBarButtonItem.title = #"Done";
//[self.editButton setTitle:#"Done" forState:UIControlStateNormal];
[self customViewHide:NO];
isDeleteButtonPress = true;
[self.tableView setEditing:YES animated:YES];
self.navigationItem.hidesBackButton = YES;
isEdited = YES;
}
}
This is my ViewWillAppear code:
-(void)viewWillAppear:(BOOL)animated{
self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"History"];
self.devices = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
self.devices=[[[self.devices reverseObjectEnumerator] allObjects] mutableCopy];
NSFetchRequest *fetchRequest1 = [[NSFetchRequest alloc] initWithEntityName:#"Favourite"];
self.fvrt = [[managedObjectContext executeFetchRequest:fetchRequest1 error:nil] mutableCopy];
self.fvrt=[[[self.fvrt reverseObjectEnumerator] allObjects] mutableCopy];
[self setHeightForSpecificRow];
isDeleteButtonPress = false;
if(self.segmentControl.selectedSegmentIndex == 0){
segment = self.devices.count;
if(segment == 0){
self.navigationItem.rightBarButtonItem.enabled = NO;
self.tableView.hidden = YES;
emptyView.hidden = NO;
if(IS_DEVICE_IPAD){
[noHistoryFavImage setImage:[UIImage imageNamed:#"no-history-ipad.png"]];
}
else{
[noHistoryFavImage setImage:[UIImage imageNamed:#"no-history-iphone.png"]];
}
emptyViewLabel1.text = #"You do not have any translation history right now.";
}
else{
self.navigationItem.rightBarButtonItem.enabled = YES;
self.tableView.hidden = NO;
emptyView.hidden = YES;
}
}
else{
segment = self.fvrt.count;
if(segment == 0){
self.navigationItem.rightBarButtonItem.enabled = NO;
self.tableView.hidden = YES;
emptyView.hidden = NO;
if(IS_DEVICE_IPAD){
[noHistoryFavImage setImage:[UIImage imageNamed:#"heart-ipad.png"]];
}
else{
[noHistoryFavImage setImage:[UIImage imageNamed:#"heart-iphone.png"]];
}
emptyViewLabel1.text = #"You do not have any favorites right now.";
}
else{
self.navigationItem.rightBarButtonItem.enabled = YES;
self.tableView.hidden = NO;
emptyView.hidden = YES;
}
}
[self.tableView reloadData];
//self.navigationController.navigationBar.tintColor = [UIColor redColor];
}

Related

iOS Replace Keyboard with UIPickerView then Back to Keyboard

I have a textfield in my app in which a user can choose a Group they belong to, along with several other fields. When they get to the Group TextField, it pops up a UIPickerView that has several choices that have already been created, along with an option to "Create New Group". When that option is chosen, I want the UIPickerView to go away, and have the keyboard pop back up so they can type again. I can get the picker view to appear and to go away, but can't get the keyboard back. Here is code so far.
-(void)addPickerView{
__block NSMutableArray *arr = [[NSMutableArray alloc] init];
PFQuery *rejectedNumber = [PFQuery queryWithClassName:#"Group"];
[rejectedNumber orderByAscending:#"GroupName"];
[rejectedNumber findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!objects) {
// Did not find any UserStats for the current user
NSLog(#"NotFound");
} else {
pickerArray = objects;
[myPickerView reloadAllComponents];
}
}];
//pickerArray = GoGo;
self.theView.signUpView.additionalField.delegate = self;
[self.theView.signUpView.additionalField setPlaceholder:#"Choose Group"];
myPickerView = [[UIPickerView alloc]init];
myPickerView.dataSource = self;
myPickerView.delegate = self;
myPickerView.showsSelectionIndicator = YES;
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc]
initWithTitle:#"Done" style:UIBarButtonItemStyleDone
target:self action:#selector(finishIt)];
UIToolbar *toolBar = [[UIToolbar alloc]initWithFrame:
CGRectMake(0, self.view.frame.size.height-
self.theView.signUpView.additionalField.frame.size.height-50, 320, 50)];
[toolBar setBarStyle:UIBarStyleBlackOpaque];
NSArray *toolbarItems = [NSArray arrayWithObjects:
doneButton, nil];
[toolBar setItems:toolbarItems];
self.theView.signUpView.additionalField.inputView = myPickerView;
self.theView.signUpView.additionalField.inputAccessoryView = toolBar;
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component{
return [pickerArray count] + 1;
}
#pragma mark- Picker View Delegate
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:
(NSInteger)row inComponent:(NSInteger)component{
if (row == 0)
[self.theView.signUpView.additionalField.inputView removeFromSuperview];
[self.theView.signUpView.additionalField becomeFirstResponder];
}
else {
[self.theView.signUpView.additionalField setText:self.theGroup];
}
}
- (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
NSString *groupName = #"Create New Group";
if (row != 0)
{
PFObject *object = pickerArray[row - 1]; // -1 to handle the array index
self.theGroup = object[#"GroupName"];
groupName = object[#"GroupName"];
}
return groupName;
}
First thing i noticed is, you missed a braces here after if condition:
if (row == 0)
[self.theView.signUpView.additionalField.inputView removeFromSuperview];
[self.theView.signUpView.additionalField becomeFirstResponder];
}
Instead use this:
if (row == 0) {
[self.theView.signUpView.additionalField resignFirstResponder];
self.theView.signUpView.additionalField.inputView = nil;
[self.theView.signUpView.additionalField becomeFirstResponder];
}

dismissViewControllerAnimated does not deallocate viewcontroller

First off: My project is ARC enabled and I'm using storyboard.
I have a view controller that pushes a segue (modal),
[self performSegueWithIdentifier: #"goInitialSettings" sender: self];
there i'm setting some parameters and store them. When the parameters are stored (true a button tap), the app should return to the original viewcontroller.
This i am doing with this command:
[self.presentingViewController dismissViewControllerAnimated:NO completion:^{}];
I'm noticing that the viewcontroller that i dismiss, never deallocs. How does this come?
I'm adding the code of the 'presented viewcontroller' below:
#interface CenterChoiceController ()
{
UIView* _titleBackground;
UILabel* _lblTitle;
UIButton* _btnGaVerder;
UIPickerView* _myPickerView;
NSArray* _centers;
UILabel* _adresLine;
UILabel* _cityLine;
MKPointAnnotation* _point;
MKMapView* _mapView;
UIActivityIndicatorView* _indicator;
UIAlertView* _alert;
GCenter* _center;
DataManager* _dm;
}
#end
#implementation CenterChoiceController
-(void)dealloc
{
NSLog(#"Centerchoice deallocs");
_titleBackground = nil;
_lblTitle = nil;
_btnGaVerder = nil;
_myPickerView = nil;
_point = nil;
_mapView = nil;
_indicator = nil;
_alert = nil;
_centers = nil;
_adresLine = nil;
_cityLine = nil;
_center = nil;
_dm = nil;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_dm = [[DataManager alloc]init];
if([_dm hasConnectivity])
{
[_dm fetchCentersForController:self];
}
else
{
[self pushErrorMessage:NSLocalizedString(#"nointernetconnection", nil)];
}
CAGradientLayer *bgLayer = [BackgroundLayer blueGradient];
bgLayer.frame = self.view.bounds;
[self.view.layer insertSublayer:bgLayer atIndex:0];
_titleBackground = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
_titleBackground.backgroundColor = [GColor blueColor];
[self.view addSubview:_titleBackground];
_lblTitle = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width - 10, 44)];
_lblTitle.textAlignment = NSTextAlignmentRight;
_lblTitle.textColor = [GColor whiteColor];
_lblTitle.text = NSLocalizedString(#"bioscoopkeuze", nil);
[self.view addSubview:_lblTitle];
_btnGaVerder = [[UIButton alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height - 54, self.view.frame.size.width, 54)];
[_btnGaVerder setTitle:NSLocalizedString(#"gaverder", nil) forState:UIControlStateNormal];
_btnGaVerder.titleLabel.font = [_btnGaVerder.titleLabel.font fontWithSize:12];
_btnGaVerder.backgroundColor = [GColor blueColor];
[_btnGaVerder setTitleColor:[GColor whiteColor] forState:UIControlStateNormal];
[_btnGaVerder setShowsTouchWhenHighlighted:YES];
[_btnGaVerder addTarget:self action:#selector(gaVerder) forControlEvents:UIControlEventTouchUpInside];
_myPickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 44, self.view.frame.size.width, 200)];
}
-(void)showLoading
{
NSLog(#"shows loading");
_indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
CGPoint cntr = self.view.center;
_indicator.center = cntr;
[_indicator startAnimating];
[self.view addSubview:_indicator];
}
-(void)hideLoading
{
NSLog(#"hides loading");
[_indicator removeFromSuperview];
_indicator = nil;
}
-(void)pushData:(NSArray *)data
{
[self.view addSubview:_btnGaVerder];
[self.view addSubview:_myPickerView];
_centers = data;
_myPickerView.delegate = self;
_myPickerView.dataSource = self;
_dm = [[DataManager alloc]init];
GSettings* settings = [_dm loadSettings];
if(settings == nil)
{
settings = [[GSettings alloc]init];
settings.chosenCenter = [_centers objectAtIndex:0];
settings.loadedCenter = [_centers objectAtIndex:0];
_center = settings.chosenCenter;
settings.notificationsEnabled = YES;
[self changeAddressLines];
}
/*if(settings != nil)
{
GCenter* loaded = settings.loadedCenter;
int i = 0;
BOOL found = NO;
while(i < [_centers count] && !found)
{
GCenter* center = (GCenter*)[_centers objectAtIndex:i];
if(settings.loadedCenter.iD == center.iD)
{
_center = center;
settings.chosenCenter = center;
[_dm storeSettings:settings];
found = YES;
}
i++;
}
//[self.myPickerView selectRow:i-1 inComponent:0 animated:NO];
loaded = nil;
[self changeAddressLines];
}
*/
}
-(void) pushErrorMessage: (NSString*) errorMessage
{
_alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"fout", nil) message:errorMessage delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
_alert.delegate = self;
[_alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(buttonIndex == 0)
{
if(self.navigationController != nil)
{
[self.navigationController popViewControllerAnimated:YES];
}
else
{
//[self initializeData];
}
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)viewWillDisappear:(BOOL)animated
{
[_dm cancelCenterRequest];
/*if(self.tabBarController != nil)
{
dm = [[DataManager alloc]init];
settings = [dm loadSettings];
if([dm hasConnectivity])
{
settings.lastUpdated = nil;
[dm storeSettings:settings];
}
if(settings.loadedCenter.centerCode != settings.chosenCenter.centerCode)
{
UIStoryboard *mystoryboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
SplashScreenController *controller = [mystoryboard instantiateViewControllerWithIdentifier:#"root"];
[self presentViewController:controller animated:YES completion:nil];
}
dm = nil;
settings = nil;
}
*/
}
-(void)gaVerder
{
_dm = [[DataManager alloc]init];
GSettings* settings = [_dm loadSettings];
if(settings == nil)
{
settings = [[GSettings alloc]init];
settings.notificationsEnabled = YES;
}
if(_center != nil)
{
settings.chosenCenter = _center;
}
[_dm storeSettings:settings];
[_mapView removeFromSuperview];
_mapView = nil;
_titleBackground = nil;
_lblTitle = nil;
_btnGaVerder = nil;
_myPickerView = nil;
_point = nil;
_indicator = nil;
_alert = nil;
_centers = nil;
_adresLine = nil;
_cityLine = nil;
_center = nil;
_dm = nil;
[self.presentingViewController dismissViewControllerAnimated:NO completion:^{}];
//DEZE BLIJFT HELAAS IN HET GEHEUGEN HANGEN... GEEN OPLOSSING GEVONDEN
//[self.navigationController popViewControllerAnimated:NO];
}
//PICKERVIEWDELEGATE EN DATASOURCE
// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return [_centers count];
}
- (UILabel *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
GCenter* center = (GCenter*)[_centers objectAtIndex:row];
NSString* string = center.name;
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, pickerView.frame.size.width, 44)];
label.textColor = [GColor blueColor];
label.font = [label.font fontWithSize:18];
label.text = string;
label.textAlignment = NSTextAlignmentCenter;
return label;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
_center = (GCenter*)[_centers objectAtIndex:row];
[self changeAddressLines];
}
-(void)changeAddressLines
{
if (_mapView != nil)
{
[_mapView removeAnnotation:_point];
}
[_adresLine removeFromSuperview];
[_cityLine removeFromSuperview];
_adresLine = nil;
_cityLine = nil;
CGRect rctAdres = CGRectMake(0, _myPickerView.frame.origin.y + _myPickerView.frame.size.height -10, self.view.frame.size.width, 20);
_adresLine = [[UILabel alloc]initWithFrame:rctAdres];
_adresLine.textAlignment = NSTextAlignmentCenter;
_adresLine.textColor = [GColor greyColor];
_adresLine.text = _center.street;
CGRect rctCity = CGRectMake(0, rctAdres.origin.y + rctAdres.size.height, self.view.frame.size.width, 20);
_cityLine = [[UILabel alloc]initWithFrame:rctCity];
_cityLine.textAlignment = NSTextAlignmentCenter;
_cityLine.textColor = [GColor greyColor];
_cityLine.font = [_cityLine.font fontWithSize:14];
_cityLine.text = _center.city;
[self.view addSubview:_adresLine];
[self.view addSubview:_cityLine];
if(_mapView == nil)
{
double height;
height = _btnGaVerder.frame.origin.y - _cityLine.frame.origin.y - _cityLine.frame.size.height;
CGRect mapRect = CGRectMake(0, _cityLine.frame.origin.y+3 + _cityLine.frame.size.height, self.view.frame.size.width, height);
_mapView = [[MKMapView alloc]initWithFrame:mapRect];
[self.view addSubview:_mapView];
}
CLLocationCoordinate2D punt;
punt.latitude = _center.latitude;
punt.longitude = _center.longitude;
_point = [[MKPointAnnotation alloc] init];
[_point setCoordinate:punt];
_mapView.centerCoordinate = punt;
_point.title = _center.name;
[_mapView addAnnotation:_point];
[_mapView setCenterCoordinate:punt animated:YES];
MKCoordinateRegion theRegion = _mapView.region;
theRegion.span.longitudeDelta = 0.005;
theRegion.span.latitudeDelta = 0.005;
[_mapView setRegion:theRegion animated:YES];
}
#end
In my case it was a little more complicated. I don't have any variable that has strong reference to my view controller, and my view controller is not a strong delegate to any property/variable contained inside this class itself. After some hard thinking and trials, I found my issue was caused by a NSTimer object defined in the interface. The timer object itself is non-repeatable, but the method invoked by it will schedule the timer again at the end, which as you can imagine would reference this method defined in my view controller again, thus causing circular references. To break out of this loop, I had to invalidate the timer before I dismiss my view controller.
As a summary, these are cases when a view controller can be blocked from deallocating after it is dismissed:
The view controller is being strongly referenced by some outside object;
The view controller is a strong delegate referenced by some object defined within the view controller itself
The dismissViewControllerAnimated:completion: block may reference to self or it has some other code block that may cause a circular references
The view controller has NSTimer objects which can invoke some methods which re-schedules the timer
There could be more, but hopefully we can capture a lot of cases with the above cases.
If your view controller is not deallocated after it is dismissed, there's probably a strong reference to that view controller somewhere in your code. ARC will always deallocate objects that doesn't have strong reference anymore.

Horizontal scrolling on a view in ios [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
How can I implement scroll view to horizontally scroll the view pages loaded from a NSDictionary. Presently i am using swipegesture but that is little slow.
What code should I implement to achieve horizontal scrolling?
i am using this code:
-(void)DownLoadData:(NSString *)indexSelect
{
{
[[SharedUtilities getInstance]AddActivityIndicatorViewOnMainThread:self.view];
}
self._parserForNewsDetail = [afaqsParser getInstance];
[[afaqsParser getInstance] setCacheNeed:TRUE];
[self._parserForNewsDetail parseWithUrl:[_arrUrlLinks objectAtIndex:[indexSelect integerValue]] UrlTypefor:nil];
NSDictionary *resultDic;
resultDic = [[[self._parserForNewsDetail getLinkAndIdDic] valueForKey:#"items"]objectAtIndex:0];
NSLog(#"Detail Dic = %#",[resultDic description]);
if (resultDic== NULL || resultDic ==nil)
{
//Check internet here
[[SharedUtilities getInstance]RemoveActivityIndicatorView];
[SharedUtilities ShowAlert:#"No Data Found" title:nil withView:self.view];
return;
}
[self performSelectorOnMainThread:#selector(SetValuesInUserInterface:) withObject: resultDic waitUntilDone:NO];
[[SharedUtilities getInstance]RemoveActivityIndicatorView];
}
-(void)SetValuesInUserInterface:(NSDictionary *)Dic
{
self._imageView1.layer.cornerRadius = 4;
self._imageView1.clipsToBounds = YES;
self._imageView1.tag = 999;
NSURL *imgurl =[NSURL URLWithString:[[Dic valueForKey:#"image"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
self._imageView1.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:imgurl]];
NSArray *subviewsArr = [self.view subviews];
for (int i=0; i<[subviewsArr count]; i++) {
if ([[subviewsArr objectAtIndex:i] isKindOfClass:[ImageDownLoader class]]) {
[[subviewsArr objectAtIndex:i] removeFromSuperview];
}
}
if ([[Dic valueForKey:#"image"] isEqual:#""])
{
// strg=[NSString stringWithFormat:#"%#, ",[Dic valueForKey:#"image"]];
_imageView1.hidden=YES;
// _txtView.frame=CGRectMake(4.0f,95.0f,310.0f,100.0f );
_txtView.frame=CGRectMake(4.0f,95.0f,_txtView.frame.size.width,_txtView.frame.size.height );
NSLog(#"NO IMAGE");
}
else{
_imageView1.hidden=NO;
_imageView1.frame=CGRectMake(4.0f,95.0f,310.0f,180.0f );
_txtView.frame=CGRectMake(4.0f,316.0f,_txtView.frame.size.width,_txtView.frame.size.height );
NSLog(#"IMAGE VISIBLE");
}
self._scrollView.scrollEnabled = YES;
self._scrollView.showsVerticalScrollIndicator = YES;
self._scrollView.showsHorizontalScrollIndicator = YES;
self._header.font = [UIFont fontWithName:#"HelveticaNeue-MediumCond" size:18];
[self._header setText: [Dic valueForKey:#"header"]];
self._header.textColor=[UIColor blackColor];
[self._publicationDate setText:[Dic valueForKey:#"PUB_DATE"]];
[self._kicker setText:[Dic valueForKey:#"kicker"]];
[self._txtView setText:[Dic valueForKey:#"ARTICLE_BODY"]];
NSString *writer;
if ([[Dic valueForKey:#"AUTHOR"] length]>2)
{
writer=[NSString stringWithFormat:#"%#, ",[Dic valueForKey:#"AUTHOR"]];
}
else
{
writer=#"";
}
NSString *city;
if ([[Dic valueForKey:#"REPORTING_CITY"] length]>2)
{
city=[NSString stringWithFormat:#", %#",[Dic valueForKey:#"REPORTING_CITY"]];
}
else
{
city=#"";
}
NSString *str = [NSString stringWithFormat:#"%#ee%#", writer,city];
//[cell._Writer setText: [tempDic valueForKey:#"writer"]];
[self._Writer setText:str];
[_txtView sizeToFit]; //added
[_txtView layoutIfNeeded]; //added
CGRect frame = self._txtView.frame;
self._txtView.frame = frame;
[_txtView setScrollEnabled:NO];
self._scrollView.contentSize = CGSizeMake(320,440+frame.size.height);
_titleLabel.frame= CGRectMake(0, self._scrollView.contentSize.height-119, [[UIScreen mainScreen] bounds].size.width, 40);
_titleLabel.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:1];
_titleLabel.textColor = [UIColor whiteColor];
_titleLabel.textAlignment = NSTextAlignmentCenter;
_titleLabel.font = [UIFont fontWithName:#"Helvetica" size:13.5];
_titleLabel.numberOfLines=2;
[self._scrollView addSubview:_titleLabel];
}
-(void)viewWillAppear:(BOOL)animated
{
self.navigationController.navigationBarHidden = YES;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_titleLabel = [[UILabel alloc] init];
lblTitle.font = [UIFont fontWithName:#"HelveticaNeue-MediumCond" size:20];
lblTitle.text=_strTitle;
NSLog(#"arrUrls %d",[_arrUrlLinks count]);
NSLog(#"strCurrentNewsSelect %#",_strCurrentNewsSelect);
[[NSNotificationCenter defaultCenter]
postNotificationName:#"DISABLEGESTURE"
object:self];
count=[_strCurrentNewsSelect integerValue];
[self performSelectorInBackground:#selector(DownLoadData:) withObject:_strCurrentNewsSelect];
if([_strCurrentNewsSelect isEqualToString:#"0"])
{
btnPreviousNews.userInteractionEnabled=FALSE;
}
else{
}
_lblNewsCount.font = [UIFont fontWithName:#"HelveticaNeue-MediumCond" size:16];
_lblNewsCount.text=[NSString stringWithFormat:#"%d/%d",[_strCurrentNewsSelect integerValue]+1,[_arrUrlLinks count]];
// Do any additional setup after loading the view from its nib.
UIButton *shareBtn = [[UIButton alloc]initWithFrame:CGRectMake(280, 340, 40, 40)];
[shareBtn addTarget:self action:#selector(Share:) forControlEvents:UIControlEventTouchUpInside];
[shareBtn setBackgroundImage:[UIImage imageNamed:#"share1.png"] forState:UIControlStateNormal];
// [self.view addSubview:shareBtn];
if([_strCurrentNewsSelect isEqualToString:#"0"])
{
btnPreviousNews.userInteractionEnabled=FALSE;
[btnPreviousNews setImage:[UIImage imageNamed:#"arrow2_prev.png"] forState:UIControlStateNormal];
}
if([_strCurrentNewsSelect isEqualToString:[NSString stringWithFormat:#"%d",[_arrUrlLinks count]-1]])
{
btnNextNews.userInteractionEnabled=FALSE;
[btnNextNews setImage:[UIImage imageNamed:#"arrow2_next.png"] forState:UIControlStateNormal];
}
UISwipeGestureRecognizer *rightRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(rightSwipeHandle:)];
rightRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
[rightRecognizer setNumberOfTouchesRequired:1];
//add the your gestureRecognizer , where to detect the touch..
[_scrollView addGestureRecognizer:rightRecognizer];
UISwipeGestureRecognizer *leftRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(leftSwipeHandle:)];
leftRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
[leftRecognizer setNumberOfTouchesRequired:1];
[_scrollView addGestureRecognizer:leftRecognizer];
}
- (void)rightSwipeHandle:(UISwipeGestureRecognizer*)gestureRecognizer
{
[self btnPreviousClick];
}
- (void)leftSwipeHandle:(UISwipeGestureRecognizer*)gestureRecognizer
{
NSLog(#"leftSwipeHandle");
[self btnNextClick];
}
-(IBAction)Share:(UIButton *)sender
{
NSLog(#"SHare called =%d",sender.tag);
// NSDictionary *tempDic = [[self._resultDic valueForKey:#"items"] objectAtIndex:sender.tag];
[[SharedUtilities getInstance] set_LinkForSharing:[[[[self._parserForNewsDetail getLinkAndIdDic] valueForKey:#"items"]objectAtIndex:0] valueForKey:#"image"]];
[[SharedUtilities getInstance]set_headerForSharing:[[[[self._parserForNewsDetail getLinkAndIdDic] valueForKey:#"items"]objectAtIndex:0] valueForKey:#"header"]];
[[SharedUtilities getInstance]set_viewController:self];
[[SharedUtilities getInstance]Share];
}
-(IBAction)btnBackPress:(id)sender;
{
[[NSNotificationCenter defaultCenter]
postNotificationName:#"ENABLEGESTURE"
object:self];
[self.navigationController popViewControllerAnimated:YES];
lblTitle.text=_strTitle;
}
-(IBAction)btnNextClick
{
btnPreviousNews.userInteractionEnabled=TRUE;
if(count!=[_arrUrlLinks count] -1)
{
if(count==[_arrUrlLinks count]-2)
{
btnNextNews.userInteractionEnabled=FALSE;
[btnNextNews setImage:[UIImage imageNamed:#"arrow2_next.png"] forState:UIControlStateNormal];
}
[btnPreviousNews setImage:[UIImage imageNamed:#"arrow1_prev.png"] forState:UIControlStateNormal];
count=count +1;
_lblNewsCount.text=[NSString stringWithFormat:#"%d/%d",count+1,[_arrUrlLinks count]];
NSLog(#"next %d",count);
[self performSelectorInBackground:#selector(DownLoadData:) withObject:[NSString stringWithFormat:#"%d",count]];
}
else{
btnNextNews.userInteractionEnabled=FALSE;
}
}
-(IBAction)btnPreviousClick
{
btnNextNews.userInteractionEnabled=TRUE;
if(count==0)
{
btnPreviousNews.userInteractionEnabled=FALSE;
}
else{
if(count==1)
{
[btnPreviousNews setImage:[UIImage imageNamed:#"arrow2_prev.png"] forState:UIControlStateNormal];
btnPreviousNews.userInteractionEnabled=FALSE;
}
[btnNextNews setImage:[UIImage imageNamed:#"arrow1_next.png"] forState:UIControlStateNormal];
count=count-1;
_lblNewsCount.text=[NSString stringWithFormat:#"%d/%d",count+1,[_arrUrlLinks count]];
NSLog(#"previous %d",count);
[self performSelectorInBackground:#selector(DownLoadData:) withObject:[NSString stringWithFormat:#"%d",count]];
}
}
}
Have you tried as like below methods,
UIScrollView * _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0, 10.0, 320.0, 280.0)];
_scrollView.backgroundColor = [UIColor clearColor];
_scrollView.pagingEnabled = YES;
_scrollView.showsHorizontalScrollIndicator = NO;
_scrollView.showsVerticalScrollIndicator = NO;
_scrollView.scrollsToTop = NO;
_scrollView.delegate = self;
[self addSubview:_scrollView];
float width = 0.0;
for (int i = 0; i < pageCount; i++)
{
UIView * yourView = [[UIView alloc] initWithFrame:CGRectMake((i * 320.0) + 20.0, 0.0, 280.0, 280.0);
[_scrollView addSubview:yourView];
width = yourView.frame.size.width + yourView.frame.origin.x + 20.0;
}
[_scrollView setContentSize:CGSizeMake(width, _scrollView.frame.size.height)];
Look at UIScrollView. To be honest this question makes it look like you've done very little research into the problem though. Can you tell us a bit more about what you currently have and what you've done so far?
UIScrollView Scroll depends on the ContentSize. So you have to set the ContentSize.
For Horizinatal Scrolling
[scroll setContentSize:CGSizeMake(1500, scroll.frame.size.height)];

iOS NSFetchedResultsController: Is it possible to use same cache for the same fetch in different View Controllers?

I have two different view controllers displaying almost the same fetch request. One of them displays more info than the other and is also used for editing of the data. The second one is just for display.
Is there a way to speed things up, since both are displaying exactly the same data? I'm looking for something in my code which makes the whole reorder slow after displaying the second view controller for the first time. In other words: Initially the reordering in my main view controller is very fast. Then you just display the second view controller and switch back and then the reordering in the main view controller gets slow. I have reason to assume that it is because they are using the same fetch.
I'm initiating the fetch request in both viewDidLoad methods, as in the following code snippets. The first one is my main view controller, and also the first one displayed when starting the app:
- (void)setupFetchedResultsController
{
self.managedObjectContext = ((AppDelegate *)[[UIApplication sharedApplication] delegate]).managedObjectContext;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"MainCategory"];
request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:#"position" ascending:YES]];
self.fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:request
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:nil cacheName:#"MainCategoryCache"];
}
And this is my second one:
- (void)setupFetchedResultsController
{
self.managedObjectContext = ((AppDelegate *)[[UIApplication sharedApplication] delegate]).managedObjectContext;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"MainCategory"];
request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:#"position" ascending:YES]];
self.fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:request
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:nil
cacheName:#"NetCache"];
}
Here are the view did load and cellForRowAtIndexPath of my main view controller:
- (void)viewDidLoad
{
[super viewDidLoad];
[self setupFetchedResultsController];
//Edit/Done button
UIBarButtonItem *editButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(#"Edit", nil) style:UIBarButtonItemStyleBordered target:self action:#selector(editTable:)];
[self.navigationItem setRightBarButtonItem:editButton];
//Budget at bottom
self.sumTitleLabel.text = [NSString stringWithFormat:#"%#%#:",NSLocalizedString(#"Budget", nil),NSLocalizedString(#"PerMonth", nil)];
self.sumLabel.text = [[DatabaseFetches budgetPerMonthForManagedObjectContext:self.managedObjectContext] getLocalizedCurrencyString];
//Layout
self.view.backgroundColor = [UIColor clearColor];
[self styleTableView];
[self styleBudgetTotal];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//Data model and cell setup
static NSString *CellIdentifier = #"MainCategoryCell";
MainCategoryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
MainCategory *mainCategory = [self.fetchedResultsController objectAtIndexPath:indexPath];
//Clear background color
cell.backgroundColor = [UIColor clearColor];
//Setup the cell texts
cell.title.text = mainCategory.name;
int numberOfSubcategories = [[mainCategory getNumberOfSpendingCategories] integerValue];
if (numberOfSubcategories == 1) {
cell.subcategories.text = [NSString stringWithFormat:#"%i %#", numberOfSubcategories, NSLocalizedString(#"subcategory", nil)];
} else {
cell.subcategories.text = [NSString stringWithFormat:#"%i %#", numberOfSubcategories, NSLocalizedString(#"subcategories", nil)];
}
cell.costs.text = [[mainCategory getMonthlyCostsOfAllSpendingCategories] getLocalizedCurrencyString];
//Delegation
cell.title.delegate = self;
//Format text
cell.title.font = [Theme tableCellTitleFont];
cell.title.textColor = [Theme tableCellTitleColor];
cell.title.tag = indexPath.row;
cell.subcategories.font = [Theme tableCellSubTitleFont];
cell.subcategories.textColor = [Theme tableCellSubTitleColor];
cell.costs.font = [Theme tableCellValueFont];
cell.costs.textColor = [Theme tableCellValueColor];
//Icon
UIImage *icon;
if(!mainCategory.icon){
icon = [UIImage imageNamed:#"DefaultIcon.png"];
} else {
icon = [UIImage imageNamed:mainCategory.icon];
}
[cell.iconButton setImage:icon forState: UIControlStateNormal];
cell.icon.image = icon;
cell.iconButton.tag = indexPath.row;
//Background image
cell.cellBackground.image = [[UIImage imageNamed:#"content-bkg"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
//Selection
//cell.title.highlightedTextColor = cell.title.textColor;
cell.subcategories.highlightedTextColor = cell.subcategories.textColor;
cell.costs.highlightedTextColor = cell.costs.textColor;
return cell;
}
Complete second view controller:
#interface NetIncomeViewController()
#property (nonatomic, strong) NSManagedObjectContext *managedObjectContext;
#end
#implementation NetIncomeViewController
#synthesize incomeTitleLabel = _incomeTitleLabel;
#synthesize incomeValueTextField = _incomeValueTextField;
#synthesize incomeBackground = _incomeBackground;
#synthesize incomeValueBackground = _incomeValueBackground;
#synthesize netIncomeTitleLabel = _netIncomeTitleLabel;
#synthesize netIncomeValueLabel = _netIncomeValueLabel;
#synthesize netIncomeBackground = _netIncomeBackground;
#synthesize netIncomeValueBackground = _netIncomeValueBackground;
#synthesize managedObjectContext = _managedObjectContext;
#pragma mark Initializer and view setup
- (void)setupFetchedResultsController
{
self.managedObjectContext = ((AppDelegate *)[[UIApplication sharedApplication] delegate]).managedObjectContext;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"MainCategory"];
request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:#"position" ascending:YES]];
self.fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:request
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
}
#pragma mark View lifecycle
- (void)awakeFromNib{
[super awakeFromNib];
//Title (necessary here because otherwise the tab bar would be only localized after first click
//on the respective tab bar and not from beginning
self.title = NSLocalizedString(#"Net Income", nil);
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self updateNetIncome];
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self setupFetchedResultsController];
//Edit/Done button
UIBarButtonItem *editButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(#"Edit", nil) style:UIBarButtonItemStyleBordered target:self action:#selector(editIncome:)];
[self.navigationItem setRightBarButtonItem:editButton];
//Get or set and get the gross income
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSNumber *grossIncome = [defaults objectForKey:#"income"];
if (!grossIncome) {
[defaults setDouble:0 forKey:#"income"];
[defaults synchronize];
grossIncome = [defaults objectForKey:#"income"];
}
self.incomeValueTextField.enabled = NO;
self.incomeValueTextField.delegate = self;
self.incomeValueTextField.keyboardType = UIKeyboardTypeDecimalPad;
self.incomeValueTextField.text = [grossIncome getLocalizedCurrencyString];
[self styleTableViewAndIncome];
}
- (void)styleTableViewAndIncome
{
self.view.backgroundColor = [UIColor clearColor];
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
self.tableView.backgroundColor = [UIColor clearColor];
self.incomeTitleLabel.textColor = [Theme budgetValueTitleColor];
self.incomeTitleLabel.font = [Theme budgetValueTitleFont];
self.incomeValueTextField.textColor = [Theme budgetValueColor];
self.incomeValueTextField.font = [Theme budgetValueTitleFont];
self.netIncomeTitleLabel.textColor = [Theme budgetValueTitleColor];
self.netIncomeTitleLabel.font = [Theme budgetValueTitleFont];
self.netIncomeValueLabel.textColor = [Theme budgetValueColor];
self.netIncomeValueLabel.font = [Theme budgetValueFont];
self.incomeTitleLabel.text = [NSString stringWithFormat:#"%#:",NSLocalizedString(#"Income", nil)];
self.netIncomeTitleLabel.text = [NSString stringWithFormat:#"%#%#:",NSLocalizedString(#"Net", nil),NSLocalizedString(#"PerMonth", nil)];
self.incomeBackground.image = [[UIImage imageNamed:#"content-bkg"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
self.incomeValueBackground.image = [[UIImage imageNamed:#"price-bkg"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
self.netIncomeBackground.image = [[UIImage imageNamed:#"content-bkg"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
}
#pragma mark Table view delegate methods
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CategoryCostCell";
CategoryCostTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
cell.backgroundColor = [UIColor clearColor];
// Configure the cell layout
MainCategory *mainCategory = [self.fetchedResultsController objectAtIndexPath:indexPath];
// Configure the cell layout
cell.categoryBackground.image = [[UIImage imageNamed:#"content-bkg"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
if(!mainCategory.icon){
cell.categoryImage.image = [UIImage imageNamed:#"DefaultIcon.png"];
} else {
cell.categoryImage.image = [UIImage imageNamed:mainCategory.icon];
}
cell.categoryName.text = mainCategory.name;
NSNumber *expenditures = [mainCategory getMonthlyCostsOfAllSpendingCategories];
double expendituresDouble =-[expenditures doubleValue];
if (expendituresDouble == 0) {
expenditures = [NSNumber numberWithDouble: 0];
} else {
expenditures = [NSNumber numberWithDouble: expendituresDouble];
}
cell.categoryCosts.text = [expenditures getLocalizedCurrencyString];
//Format the text
cell.categoryName.font = [Theme tableCellSmallTitleFont];
cell.categoryName.textColor = [Theme tableCellSmallTitleColor];
cell.categoryCosts.font = [Theme tableCellSmallValueFont];
cell.categoryCosts.textColor = [Theme tableCellSmallValueColor];
return cell;
}
#pragma mark TextField delegate methods
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
if(self.editing){
return YES;
} else {
return NO;
}
}
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
textField.text = [NSString stringWithFormat:#"%.2f",[NSNumber getUnLocalizedCurrencyDoubleWithString:textField.text]];
}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
textField.text = [[NSNumber numberWithDouble:[textField.text doubleValue]] getLocalizedCurrencyString];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
//Handle the enter button
[textField resignFirstResponder];
[self endEdit];
//Since this method is called AFTER DidEndEditing, we have to call editTable or in this case since we have put all the endEdit code in a seperate method this method directly in order to format the table back from edit mode to normal.
return YES;
}
#pragma mark Edit/Add/Delete action
- (IBAction) editIncome:(id)sender
{
if(self.editing)
{
[self endEdit];
} else {
[self beginEdit];
}
}
- (void) beginEdit
{
//Change to editing mode
[super setEditing:YES animated:YES];
//Exchange the edit button with done button
[self.navigationItem.rightBarButtonItem setTitle:NSLocalizedString(#"Done", nil)];
[self.navigationItem.rightBarButtonItem setStyle:UIBarButtonItemStyleDone];
self.incomeValueTextField.borderStyle = UITextBorderStyleRoundedRect;
self.incomeValueTextField.enabled = YES;
self.incomeValueBackground.hidden = YES;
self.incomeValueTextField.textColor = [Theme budgetValueTitleColor];
}
- (void) endEdit
{
//Change to editing no
[super setEditing:NO animated:YES];
//Remove Done button and exchange it with edit button
[self.navigationItem.rightBarButtonItem setTitle:NSLocalizedString(#"Edit", nil)];
[self.navigationItem.rightBarButtonItem setStyle:UIBarButtonItemStylePlain];
self.incomeValueTextField.borderStyle = UITextBorderStyleNone;
self.incomeValueTextField.enabled = NO;
self.incomeValueBackground.hidden = NO;
self.incomeValueTextField.textColor = [Theme budgetValueColor];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setDouble:[NSNumber getUnLocalizedCurrencyDoubleWithString:self.incomeValueTextField.text] forKey:#"income"];
[self updateNetIncome];
//[defaults synchronize];
}
#pragma mark Net income
- (void) updateNetIncome {
double grossIncome = [NSNumber getUnLocalizedCurrencyDoubleWithString:self.incomeValueTextField.text];
double budget = [[DatabaseFetches budgetPerMonthForManagedObjectContext:self.managedObjectContext] doubleValue];
double netIncome = grossIncome - budget;
if(netIncome >0){
self.netIncomeValueBackground.image = [[UIImage imageNamed:#"price-bkg_green"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
} else if(netIncome <0) {
self.netIncomeValueBackground.image = [[UIImage imageNamed:#"price-bkg_red"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
} else {
self.netIncomeValueBackground.image = [[UIImage imageNamed:#"price-bkg"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
}
self.netIncomeValueLabel.text = [[NSNumber numberWithDouble:netIncome] getLocalizedCurrencyString];
}
#end
It looks like you're doing UIImage creation in your cellForRowAtIndexPath method, which would cause a slowdown.
Better to create the background UIImage as an instance variables and set its image in the viewDidLoad, then reference it in the cellForRowAtIndexPath method. Like so:
//Declare the instance variable
UIImage *backgroundImage
//Set it in viewDidLoad
self.backgroundImage = [[UIImage imageNamed:#"content-bkg"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
//Assign it in cellForRowAtIndexPath
cell.backgroundImage = self.backgroundImage;
As for the icon, which has to be set for each row, you'll want to move the actual image loading off the main thread. You can do this either with dispatch_async() or NSOperationQueue. (pulled from here: Understanding dispatch_async)
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
UIImage *icon;
if(!mainCategory.icon){
icon = [UIImage imageNamed:#"DefaultIcon.png"];
} else {
icon = [UIImage imageNamed:mainCategory.icon];
}
dispatch_async(dispatch_get_main_queue(), ^(void){
[cell.iconButton setImage:icon forState: UIControlStateNormal];
cell.icon.image = icon;
cell.iconButton.tag = indexPath.row;
});
});
Notice how the imageNamed method is called in the background thread, but the actual assignment takes place on the main thread. You have to do it this way because you're not allowed to update UI elements anywhere except the main thread.

How do I use a for loop to display NSArray of UIImage's

Hey guys,
So.... lets say I have an NSArray of images
NSMutableArray *images = [NSMutableArray new];
[images addObject:[UIImage imageNamed:#"line1.png"]];
[images addObject:[UIImage imageNamed:#"line2.png"]];
[images addObject:[UIImage imageNamed:#"line3.png"]];
[images addObject:[UIImage imageNamed:#"line4.png"]];
Now I would like to load all these at once using a for loop but here is the catch.... I need to be able to set the images as hidden until the user unhides through interaction.
for (UIImage *image in images) {
UIImageView *line = [[UIImageView alloc] initWithImage:image];
line.hidden = YES;
[self.view addSubview:line];
}
But then how to I set the hidden BOOL to NO using another method?
As a secondary question, how would one release *line in the code above?
Thanks,
Darren
One option is to set up your images like:
int nextTag = 1;
for (UIImage *image in images) {
UIImageView *line = [[UIImageView alloc] initWithImage:image];
line.hidden = YES;
line.tag = nextTag;
[self.view addSubview:line];
[line release];
nextTag++;
}
...and then to unhide them you can do:
UIView* imageView = [self.view viewWithTag: lineNumber];
imageView.hidden = NO;
...assuming that your user-interaction handler is able to determine what line in the UI the user is interacting with.
As a secondary question, how would one release *line in the code above?
for (UIImage *image in images) {
UIImageView *line = [[UIImageView alloc] initWithImage:image];
line.hidden = YES;
[self.view addSubview:line]; // this retains the subview.
[line release]; // release line like this.
}
**
-(IBAction)btnReviewStar:(id)sender{
for (int i =([sender tag] ==30); i<36; i++) {
btnReviewStar.selected = NO;
btnReviewStar1.selected = NO;
btnReviewStar2.selected = NO;
btnReviewStar3.selected = NO;
btnReviewStar4.selected = NO;
if([sender tag] == 31) {
btnReviewStar.selected = YES;
break;
} else if([sender tag]==32) {
btnReviewStar.selected = YES;
btnReviewStar1.selected = YES;
break;
} else if([sender tag]==33) {
btnReviewStar.selected = YES;
btnReviewStar1.selected = YES;
btnReviewStar2.selected = YES;
break;
} else if([sender tag]==34) {
btnReviewStar.selected = YES;
btnReviewStar1.selected = YES;
btnReviewStar2.selected = YES;
btnReviewStar3.selected = YES;
break;
} else {
btnReviewStar.selected = YES;
btnReviewStar1.selected = YES;
btnReviewStar2.selected = YES;
btnReviewStar3.selected = YES;
btnReviewStar4.selected = YES;
break;
}
}
}
**

Resources