First picker row selection changes second picker row - objective-c

Ive picked up some code form another developer which im trying to put right. One of the problems is:
I have 2 pickers that fill a text box with selected row from a picker.
If picker 1 (named: Type) is selected, the row selected ..say row 3, defaults to that row on my next picker (named: FlueType) when the picker is presented.
How can I get the second picker not be affected by the first pickers row selection?
Ive looked at [picker reloadComponent:0]; I've looked on stack and google and cant seem to find anything that fits this problem.
Ive also tried [picker selectRow:0 inComponent:0 animated:NO] in the ViewDidLoad method hoping that it would set all my pickers to the first row value which is all im trying to do.
Apologies for the mountain of code, I've tried to separate it out into context
/////////////////////picker action////////////////////////
-(void)flueTypeBtnClicked//:(id)sender
{
[flueTypeBtn.titleLabel setTextColor:[UIColor blackColor]];
currentSelectedIndex = flueTypeBtn.tag;
[makeTxt resignFirstResponder];
[modelTxt resignFirstResponder];
[locationTxt resignFirstResponder];
[oprPressureMBarTxt resignFirstResponder];
[picker setHidden:NO];
[picker reloadComponent:0];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.3];
self.ToolsView.frame = CGRectMake(0, 200, 320, 260);
extern GasCertificateAppViewController *viewController;
[viewController.view addSubview:self.ToolsView];
[UIView commitAnimations];
}
-(void)typeBtnClicked//:(id)sender
{
[typeBtn.titleLabel setTextColor:[UIColor blackColor]];
currentSelectedIndex = typeBtn.tag;
[makeTxt resignFirstResponder];
[modelTxt resignFirstResponder];
[locationTxt resignFirstResponder];
[oprPressureMBarTxt resignFirstResponder];
[picker setHidden:NO];
[picker reloadComponent:0];
//NSLog(#"In type btn Clicked:");
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.3];
self.ToolsView.frame = CGRectMake(0, 200, 320, 260);
extern GasCertificateAppViewController *viewController;
[viewController.view addSubview:self.ToolsView];
[UIView commitAnimations];
///////////////////////////////////////////////////////////////////////////////////////////////////////////////more code here///////////////////////
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
if (textField.tag == 1 )
{
[self typeBtnClicked];
return NO;
}
else if(textField.tag == 3)
{
[self flueTypeBtnClicked];
return NO;
}
CGPoint offset = CGPointMake(0, textField.frame.origin.y - textField.frame.size.height);
[self.screenScrollView setContentOffset: offset animated: YES];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.3];
self.ToolsView.frame = CGRectMake(0, 200, 320, 260);
extern GasCertificateAppViewController *viewController;
[viewController.view addSubview:self.ToolsView];
[UIView commitAnimations];
return YES;
}
//////////////
-(void) fillData
{
extern Survey *survey;
ApplianceTest *test = [survey.applianceTestArray objectAtIndex:testId];
if(test.type != nil)
[self.typeTxt setText:test.type];
// [self.typeBtn setTitle:test.type forState:UIControlStateNormal];
if(test.make != nil)
[self.makeTxt setText:test.make];
if(test.model != nil)
[self.modelTxt setText:test.model];
if(test.location != nil)
[self.locationTxt setText:test.location];
if(test.flue_type != nil)
[self.flueTypeTxt setText:test.flue_type];
//[self.flueTypeBtn setTitle:test.flue_type forState:UIControlStateNormal]; if(test.operating_pressure_mbar_or_heat_input_kwh != nil)
[self.oprPressureMBarTxt setText:test.operating_pressure_mbar_or_heat_input_kwh];
if([test.safety_device_correct isEqualToString:#"Yes"])
[self.segtCtrl setSelectedSegmentIndex:0];
else
if([test.safety_device_correct isEqualToString:#"No"])
[self.segtCtrl setSelectedSegmentIndex:1];
else
[self.segtCtrl setSelectedSegmentIndex:2];
}
-(IBAction)bgTouched:(id)sender
{
CGPoint offset = CGPointMake(0, 0);
[self.screenScrollView setContentOffset: offset animated: YES];[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.3];
self.ToolsView.frame = CGRectMake(0, 500, 320,260);
//[self.ToolsView removeFromSuperview];
//self.view.frame = CGRectMake(0, 0, 320, 372 );
[makeTxt resignFirstResponder];
[modelTxt resignFirstResponder];
[locationTxt resignFirstResponder];
[oprPressureMBarTxt resignFirstResponder];
[UIView commitAnimations];
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)viewDidLoad {
[super viewDidLoad];
//segment control selected Index = 2;
segtCtrl.selectedSegmentIndex = 2;
navigationTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(130, 0, 200, 25)];
navigationTitleLabel.textAlignment = UITextAlignmentCenter;
navigationTitleLabel.font= [UIFont fontWithName:#"Futura" size:18];
navigationTitleLabel.backgroundColor = [UIColor clearColor];
navigationTitleLabel.textColor = [UIColor whiteColor];
navigationTitleLabel.text = #"Appliance Test 1/3";
self.navigationItem.titleView = navigationTitleLabel;
self.screenScrollView.frame = CGRectMake(0, 0, 320, 370);
self.screenScrollView.contentSize = CGSizeMake(320, 600 + 200);
self.screenScrollView.clipsToBounds = YES;
self.screenScrollView.showsVerticalScrollIndicator = NO;
[self.view addSubview:self.screenScrollView];
testId = [testIdStr intValue];
currentSelectedIndex = 0;
typeArray = [[NSMutableArray alloc] init];
[typeArray addObject:#""]; ///change
[typeArray addObject:#"Boiler"];
[typeArray addObject:#"Cooker"];
[typeArray addObject:#"Fire"];
[typeArray addObject:#"Hob"]; ///change to hob
currentSelectedIndex = 0;
flueTypeArray = [[NSMutableArray alloc] init];
[flueTypeArray addObject:#""]; //change
[flueTypeArray addObject:#"OF"];
[flueTypeArray addObject:#"RS"];
[flueTypeArray addObject:#"FL"];
unitArray = [[NSMutableArray alloc] initWithObjects:#"MBar",#"KW/h",nil];
//self.navigationItem.title = #"Appliance Test 1/3";
//[typeTableView setHidden:YES];
//[flueTypeTableView setHidden:YES];
[segtCtrl setSelectedSegmentIndex:2];
extern Survey *survey;
[self fillData];
[picker setHidden:YES];
self.ToolsView.frame = CGRectMake(0, 500, 320, 260);
/////////////////
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent: (NSInteger)component
{
if (currentSelectedIndex == 1)
{
return [typeArray count];
}
else if(currentSelectedIndex == 3)
{
return [flueTypeArray count];
}
else if(currentSelectedIndex == 7)
{
return [unitArray count];
}
else
{
return 1;
}
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
if (currentSelectedIndex == 1)
{
if ([typeArray count] == 0)
{
return [NSString stringWithFormat: #"None"];
}
else
{
return [typeArray objectAtIndex:row];
}
}
else if(currentSelectedIndex == 3)
{
if ([flueTypeArray count] == 0)
{
return [NSString stringWithFormat: #"None"];
}
else {
return [flueTypeArray objectAtIndex:row];
}
}
else if(currentSelectedIndex == 7)
{
if ([unitArray count] == 0)
{
return [NSString stringWithFormat: #"None"];
}
else
{
return [unitArray objectAtIndex:row];
}
}
return #"";
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
// [gasSafeNoBtn setTitle:[NSString stringWithFormat:#"%d",[(NSNumber *) [gasSafeNoArray objectAtIndex:row]intValue]] forState:UIControlStateNormal];
extern Survey *survey;
if (currentSelectedIndex==1)
{
//typeTxt.text = [typeArray objectAtIndex:row];
[typeBtn.titleLabel setTextColor:[UIColor blackColor]];
[typeBtn setTitle:[typeArray objectAtIndex:row] forState:UIControlStateNormal];
typeTxt.text =[typeArray objectAtIndex:row] ;
}
else if(currentSelectedIndex == 3)
{
//flueTypeTxt.text = [flueTypeArray objectAtIndex:row];
[flueTypeBtn.titleLabel setTextColor:[UIColor blackColor]];
[flueTypeBtn setTitle:[flueTypeArray objectAtIndex:row] forState:UIControlStateNormal];
flueTypeTxt.text= [flueTypeArray objectAtIndex:row];
}
else if(currentSelectedIndex == 7)
{
unitString = [[NSString alloc] initWithString:[unitArray objectAtIndex:row]];
// NSLog(#"Unit String : %#", unitString);
[unitBtn setTitle:[unitArray objectAtIndex:row] forState:UIControlStateNormal];
}
else {
}
}
- (void)dealloc {
[unitArray release];
[ToolsView release];
[toolBar release];
[nextBtn release];
[prevBtn release];
[doneBtn release];
[picker release];
[super dealloc];
}
#end

Ok sorted....added
[picker selectRow:0 inComponent:0 animated:NO];
to the button action method presenting the picker

Related

2 Player setup not showing after 1 player mode is previously selected

I'm a newbie ... I'm making a 2 player game. At the main menu, if 1 player mode is selected and then you play or go back to main menu and select 2 Player mode, the 2 player mode doesn't show the 2 player mode setup screen correctly.
If 2 player mode is selected before 1 player mode ever is, then it shows the 2 player mode setup screen fine. Below is my onePlayerViewController:
-(void)viewWillAppear:(BOOL)animated {
if ([[[NSUserDefaults standardUserDefaults] valueForKey:kGameType] isEqualToString:#"1Player"])
{
vwPlayer2.hidden=TRUE;
if (IDIOM == IPAD){
lblHeading.frame = CGRectMake(lblHeading.frame.origin.x, lblHeading.frame.origin.y+100, lblHeading.frame.size.width, lblHeading.frame.size.height);
vwCenter.frame = CGRectMake(vwCenter.frame.origin.x, vwCenter.frame.origin.y, vwCenter.frame.size.width, 644);
vwLevel.frame = CGRectMake(vwLevel.frame.origin.x,vwLevel.frame.origin.y, vwLevel.frame.size.width, vwLevel.frame.size.height);
vwPlayer1.frame = CGRectMake(vwPlayer1.frame.origin.x,vwPlayer2.frame.origin.y, vwPlayer1.frame.size.width, vwPlayer1.frame.size.height);
}else {
lblHeading.frame = CGRectMake(lblHeading.frame.origin.x, 115, lblHeading.frame.size.width, lblHeading.frame.size.height);
vwCenter.frame = CGRectMake(vwCenter.frame.origin.x, 187, vwCenter.frame.size.width, 200);
vwLevel.frame = CGRectMake(vwLevel.frame.origin.x, 105, vwLevel.frame.size.width, vwLevel.frame.size.height);
}
lblHeading.text = #"1 Player";
txtPlayerName1.text = #"Player 1";
if ([[[NSUserDefaults standardUserDefaults] valueForKey:kPlayerName1] length]!=0)
{
txtPlayerName1.text = [[NSUserDefaults standardUserDefaults] valueForKey:kPlayerName1];
}
}
else if ([[[NSUserDefaults standardUserDefaults] valueForKey:kGameType] isEqualToString:#"2Player"])
{
vwPlayer2.hidden=FALSE;
vwLevel.hidden=FALSE;
if (IDIOM == IPAD){
lblHeading.frame = CGRectMake(lblHeading.frame.origin.x, lblHeading.frame.origin.y, lblHeading.frame.size.width, lblHeading.frame.size.height);
vwCenter.frame = CGRectMake(vwCenter.frame.origin.x, vwCenter.frame.origin.y, vwCenter.frame.size.width, 644);
vwPlayer1.frame = CGRectMake(vwPlayer1.frame.origin.x,vwPlayer1.frame.origin.y, vwPlayer1.frame.size.width, vwPlayer1.frame.size.height);
vwPlayer2.frame = CGRectMake(vwPlayer2.frame.origin.x,vwPlayer2.frame.origin.y, vwPlayer2.frame.size.width, vwPlayer2.frame.size.height);
vwLevel.frame = CGRectMake(vwLevel.frame.origin.x,vwLevel.frame.origin.y, vwLevel.frame.size.width, vwLevel.frame.size.height);
}else{
if ([UIScreen mainScreen].bounds.size.height == 568)
{
lblHeading.frame = CGRectMake(lblHeading.frame.origin.x, 89, lblHeading.frame.size.width, lblHeading.frame.size.height);
vwCenter.frame = CGRectMake(vwCenter.frame.origin.x, 135, vwCenter.frame.size.width, 310);
}
else
{
lblHeading.frame = CGRectMake(lblHeading.frame.origin.x, 72, lblHeading.frame.size.width, lblHeading.frame.size.height);
vwCenter.frame = CGRectMake(vwCenter.frame.origin.x, 101, vwCenter.frame.size.width, 312);
}
}
lblHeading.text = #"2 Players";
txtPlayerName1.text = #"Player 1";
txtPlayerName2.text = #"Player 2";
if ([[[NSUserDefaults standardUserDefaults] valueForKey:kPlayerName1] length]!=0)
{
txtPlayerName1.text = [[NSUserDefaults standardUserDefaults] valueForKey:kPlayerName1];
}
if ([[[NSUserDefaults standardUserDefaults] valueForKey:kPlayerName2] length]!=0)
{
txtPlayerName2.text = [[NSUserDefaults standardUserDefaults] valueForKey:kPlayerName2];
}
}
else
{
vwPlayer2.hidden=TRUE;
vwLevel.hidden=TRUE;
if (IDIOM == IPAD){
lblHeading.frame = CGRectMake(lblHeading.frame.origin.x, lblHeading.frame.origin.y, lblHeading.frame.size.width, lblHeading.frame.size.height);
vwCenter.frame = CGRectMake(vwCenter.frame.origin.x, vwCenter.frame.origin.y, vwCenter.frame.size.width, 644);
}else{
lblHeading.frame = CGRectMake(lblHeading.frame.origin.x, 115, lblHeading.frame.size.width, lblHeading.frame.size.height);
vwCenter.frame = CGRectMake(vwCenter.frame.origin.x, 187, vwCenter.frame.size.width, 200);
}
lblHeading.text = #"Player";
txtPlayerName1.text = #"Player 1";
[[NSUserDefaults standardUserDefaults] setValue:nil forKeyPath:kPlayerName1];
[[NSUserDefaults standardUserDefaults] setValue:nil forKeyPath:kPlayerName2];
[[NSUserDefaults standardUserDefaults] setValue:nil forKey:kTurn];
if ([[[NSUserDefaults standardUserDefaults] valueForKey:kWifiPlayerName] length]!=0)
{
txtPlayerName1.text = [[NSUserDefaults standardUserDefaults] valueForKeyPath:kWifiPlayerName];
}
else
{
txtPlayerName1.text = #"Player 1";
}
}
I have tried using [[NSUserDefaults standardUserDefaults] removeObjectForKey:#"kGameType"];
[[NSUserDefaults standardUserDefaults] synchronize]; but i'm guessing that I am putting it in the wrong place??
HomeViewController -
-(void)viewWillAppear:(BOOL)animated {
if (!gameCenterEnabled)
{
[self notAnimate];
}
else
{
btnPlayer1.frame=CGRectMake(btnPlayer1.center.x, btnPlayer1.center.y, 0, 0);
btnPlayer2.frame=CGRectMake(btnPlayer2.center.x, btnPlayer2.center.y, 0, 0);
btnWifi.frame=CGRectMake(btnWifi.center.x, btnWifi.center.y, 0, 0);
btnInfo.frame=CGRectMake(btnInfo.center.x, btnInfo.center.y, 0, 0);
UILabel *lbl1 = (UILabel *)[self.view viewWithTag:1];
UILabel *lbl2 = (UILabel *)[self.view viewWithTag:2];
UILabel *lbl3 = (UILabel *)[self.view viewWithTag:3];
UILabel *lbl4 = (UILabel *)[self.view viewWithTag:4];
lbl1.alpha=1.0;
lbl2.alpha=1.0;
lbl3.alpha=1.0;
lbl4.alpha=1.0;
lbl1.frame=CGRectMake(lbl1.center.x,lbl1.center.y,0,0);
lbl2.frame=CGRectMake(lbl2.center.x,lbl2.center.y,0,0);
lbl3.frame=CGRectMake(lbl3.center.x,lbl3.center.y,0,0);
lbl4.frame=CGRectMake(lbl4.center.x,lbl4.center.y,0,0);
btnInfo.alpha = 1.0;
btnWifi.alpha = 1.0;
btnPlayer1.alpha = 1.0;
btnPlayer2.alpha = 1.0;
imgLogo.frame=CGRectMake(imgLogo.frame.origin.x, -imgLogo.frame.size.height, imgLogo.frame.size.width, imgLogo.frame.size.height);
vwBottom.frame = CGRectMake(vwBottom.frame.origin.x, self.view.frame.size.height+vwBottom.frame.size.height, vwBottom.frame.size.width, vwBottom.frame.size.height);
[self viewLoadAnimationForLogo];
[self animationOnButton];
[self animationOnLabel];
[self animationOnBottomButton];
[self.view setUserInteractionEnabled:TRUE];
}
gameCenterEnabled = YES; }
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
//Actions
-(IBAction)btnActions:(UIButton *)sender
{
NSNumber *numTag = [NSNumber numberWithInt:(int)sender.tag];
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults removeObjectForKey:kGameType];
//do this for all your keys..
[defaults synchronize];
}
self.view.userInteractionEnabled = FALSE;
switch (sender.tag)
{
//1 Player button
case 11:
[[NSUserDefaults standardUserDefaults] setValue:#"1Player" forKey:kGameType];
[UIView beginAnimations:#"animateSelection1" context:nil];
[UIView setAnimationDuration:animationDuration];
[self removeSubviewsbyAnimations];
if (IDIOM == IPAD){
[btnPlayer1 setImage:[UIImage imageNamed:#"icn1PlayerS_iPad.png"] forState:UIControlStateNormal];
}else{
[btnPlayer1 setImage:[UIImage imageNamed:#"icn1PlayerS.png"] forState:UIControlStateNormal];
}
btnPlayer2.frame=CGRectMake(btnPlayer2.center.x,btnPlayer2.center.y,0, 0);
btnWifi.frame=CGRectMake(btnWifi.center.x,btnWifi.center.y,0, 0);
btnInfo.frame=CGRectMake(btnInfo.center.x,btnInfo.center.y,0, 0);
btnPlayer1.frame=CGRectMake(btnPlayer1.frame.origin.x-btnPlayer1.frame.size.width/2, btnPlayer1.frame.origin.y-btnPlayer1.frame.size.height/2, btnPlayer1.frame.size.width*2.0, btnPlayer1.frame.size.height*2.0);
btnPlayer1.alpha = 0.0;
[UIView commitAnimations];
[self performSelector:#selector(performButtonAction:) withObject:numTag afterDelay:animationDuration];
break;
//2 Player button
case 12:
{
[[NSUserDefaults standardUserDefaults] setValue:#"2Player" forKey:kGameType];
[UIView beginAnimations:#"animateSelection2" context:nil];
[UIView setAnimationDuration:animationDuration];
[self removeSubviewsbyAnimations];
if (IDIOM == IPAD){
[btnPlayer2 setImage:[UIImage imageNamed:#"icn2PlayerS_iPad.png"] forState:UIControlStateNormal];
}else{
[btnPlayer2 setImage:[UIImage imageNamed:#"icn2PlayerS.png"] forState:UIControlStateNormal];
}
btnPlayer1.frame=CGRectMake(btnPlayer1.center.x,btnPlayer1.center.y,0, 0);
btnWifi.frame=CGRectMake(btnWifi.center.x,btnWifi.center.y,0, 0);
btnInfo.frame=CGRectMake(btnInfo.center.x,btnInfo.center.y,0, 0);
btnPlayer2.frame=CGRectMake(btnPlayer2.frame.origin.x-btnPlayer2.frame.size.width/2, btnPlayer2.frame.origin.y-btnPlayer2.frame.size.height/2, btnPlayer2.frame.size.width*2, btnPlayer2.frame.size.height*2);
btnPlayer2.alpha = 0.0;
[UIView commitAnimations];
[self performSelector:#selector(performButtonAction:) withObject:numTag afterDelay:animationDuration+0.2];
break;
}
// Wifi play button
case 13:
[[NSUserDefaults standardUserDefaults] setValue:#"WifiPlayer" forKey:kGameType];
[UIView beginAnimations:#"animateSelection3" context:nil];
[UIView setAnimationDuration:animationDuration];
[self removeSubviewsbyAnimations];
if (IDIOM == IPAD){
[btnWifi setImage:[UIImage imageNamed:#"icnWifiPlayS_iPad.png"] forState:UIControlStateNormal];
}else{
[btnWifi setImage:[UIImage imageNamed:#"icnWifiPlayS.png"] forState:UIControlStateNormal];
}
btnPlayer1.frame=CGRectMake(btnPlayer1.center.x,btnPlayer1.center.y,0, 0);
btnPlayer2.frame=CGRectMake(btnPlayer2.center.x,btnPlayer2.center.y,0, 0);
btnInfo.frame=CGRectMake(btnInfo.center.x,btnInfo.center.y,0, 0);
btnWifi.frame=CGRectMake(btnWifi.frame.origin.x-btnWifi.frame.size.width/2, btnWifi.frame.origin.y-btnWifi.frame.size.height/2, btnWifi.frame.size.width*2, btnWifi.frame.size.height*2);
btnWifi.alpha = 0.0;
[UIView commitAnimations];
[self performSelector:#selector(performButtonAction:) withObject:numTag afterDelay:animationDuration+0.2];
break;
//Info button
case 14:
[UIView beginAnimations:#"animateSelection4" context:nil];
[UIView setAnimationDuration:animationDuration];
[self removeSubviewsbyAnimations];
if (IDIOM == IPAD){
[btnInfo setImage:[UIImage imageNamed:#"icnInfoS_iPad.png"] forState:UIControlStateNormal];
}else{
[btnInfo setImage:[UIImage imageNamed:#"icnInfoS.png"] forState:UIControlStateNormal];
}
btnPlayer1.frame=CGRectMake(btnPlayer1.center.x,btnPlayer1.center.y,0, 0);
btnPlayer2.frame=CGRectMake(btnPlayer2.center.x,btnPlayer2.center.y,0, 0);
btnWifi.frame=CGRectMake(btnWifi.center.x,btnWifi.center.y,0, 0);
btnInfo.frame=CGRectMake(btnInfo.frame.origin.x-btnInfo.frame.size.width/2, btnInfo.frame.origin.y-btnInfo.frame.size.height/2, btnInfo.frame.size.width*2, btnInfo.frame.size.height*2);
btnInfo.alpha = 0.0;
[UIView commitAnimations];
[self performSelector:#selector(performButtonAction:) withObject:numTag afterDelay:animationDuration+0.2];
break;
//Setting & score button
default:
[UIView beginAnimations:#"animateSelection5" context:nil];
[UIView setAnimationDuration:animationDuration];
[self removeSubviewsbyAnimations];
btnPlayer1.frame=CGRectMake(btnPlayer1.center.x,btnPlayer1.center.y,0, 0);
btnPlayer2.frame=CGRectMake(btnPlayer2.center.x,btnPlayer2.center.y,0, 0);
btnWifi.frame=CGRectMake(btnWifi.center.x,btnWifi.center.y,0, 0);
btnInfo.frame=CGRectMake(btnInfo.center.x,btnInfo.center.y,0, 0);
[UIView commitAnimations];
[self performSelector:#selector(performButtonAction:) withObject:numTag afterDelay:animationDuration-0.1];
break;
}
}
Screenshots as I may not be very good at explaining what I mean
1 Player Mode
2 Player Mode after 1 Player Mode has been previously selected
Any advice, greatly appreciated

UIPickerView with UIActionSheet IOS 8 stop working

Showing a UIPickerView with UIActionSheet in iOS8 not showing
-(void)showPicker{
/************************ FIXED please contact me on nfsarmento#hotmail.com if you need help to fix******//
actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
[actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
CGRect pickerFrame = CGRectMake(0, 40, 0, 0);
UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:pickerFrame];
pickerView.showsSelectionIndicator = YES;
switch((uint)currentDelegate){
case 0:{
pickerView.dataSource = propertyDelegate;
pickerView.delegate = propertyDelegate;
[pickerView selectRow:[propertyDelegate index] inComponent:0 animated:NO];
break;
}
case 1:{
pickerView.dataSource = regionDelegate;
pickerView.delegate = regionDelegate;
[pickerView selectRow:[regionDelegate index] inComponent:0 animated:NO];
break;
}
case 2:{
pickerView.dataSource = townDelegate;
pickerView.delegate = townDelegate;
[pickerView selectRow:[townDelegate index] inComponent:0 animated:NO];
break;
}
case 3:{
pickerView.dataSource = bedDelegate;
pickerView.delegate = bedDelegate;
[pickerView selectRow:[bedDelegate index] inComponent:0 animated:NO];
break;
}
case 4:{
pickerView.dataSource = bathDelegate;
pickerView.delegate = bathDelegate;
[pickerView selectRow:[bathDelegate index] inComponent:0 animated:NO];
break;
}
case 5:{
pickerView.dataSource = priceDelegate;
pickerView.delegate = priceDelegate;
[pickerView selectRow:[priceDelegate index1] inComponent:0 animated:NO];
[pickerView selectRow:[priceDelegate index2] inComponent:1 animated:NO];
break;
}
case 6:{
pickerView.dataSource = currencyDelegate;
pickerView.delegate = currencyDelegate;
[pickerView selectRow:[currencyDelegate index] inComponent:0 animated:NO];
break;
}
}
[actionSheet addSubview:pickerView];
UISegmentedControl *previousButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:NSLocalizedString(#"Previous", nil)]];
previousButton.momentary = YES;
previousButton.frame = CGRectMake(5.0f, 7.0f, 70.0f, 30.0f);
previousButton.segmentedControlStyle = UISegmentedControlStyleBar;
previousButton.tintColor = [UIColor blackColor];
UISegmentedControl *nextButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:NSLocalizedString(#"Next", nil)]];
nextButton.momentary = YES;
nextButton.frame = CGRectMake(80.0f, 7.0f, 70.0f, 30.0f);
nextButton.segmentedControlStyle = UISegmentedControlStyleBar;
nextButton.tintColor = [UIColor blackColor];
UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:NSLocalizedString(#"Done", nil)]];
closeButton.momentary = YES;
closeButton.frame = CGRectMake(240, 7.0f, 70.0f, 30.0f);
closeButton.segmentedControlStyle = UISegmentedControlStyleBar;
closeButton.tintColor = [UIColor colorWithRed:0.35f green:0.55f blue:1.5f alpha:1.0f];
[closeButton addTarget:self action:#selector(hidePicker) forControlEvents:UIControlEventValueChanged];
[previousButton addTarget:self action:#selector(previousPicker) forControlEvents:UIControlEventValueChanged];
[nextButton addTarget:self action:#selector(nextPicker) forControlEvents:UIControlEventValueChanged];
if(currentDelegate > 0)[actionSheet addSubview:previousButton];
if(currentDelegate < 6)[actionSheet addSubview:nextButton];
[actionSheet addSubview:closeButton];
[actionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
[actionSheet setBounds:CGRectMake(0, 0, 320, 485)];
}
-(void) nextPicker{
[self hidePicker];
currentDelegate++;
[self showPicker];
}
-(void) previousPicker{
[self hidePicker];
currentDelegate--;
[self showPicker];
}
-(void)hidePicker{
switch ((uint)currentDelegate) {
case 0:{
[tf_type setText: [propertyDelegate.values objectAtIndex: [propertyDelegate index]]];
_appDelegate.int_typeV = [propertyDelegate index];
break;
}
case 1:{
[tf_region setText: [regionDelegate.values objectAtIndex: [regionDelegate index]]];
_appDelegate.int_regionV = [regionDelegate index];
//Reset Town dropdown when a region is picked
_appDelegate.int_townV = 0;
townDelegate = [[TownDelegate alloc] init];
[self.tf_town setText: [townDelegate.values objectAtIndex: [_appDelegate int_townV]]];
break;
}
case 2:{
[tf_town setText: [townDelegate.values objectAtIndex: [townDelegate index]]];
_appDelegate.int_townV = [townDelegate index];
break;
}
case 3:{
[tf_numBed setText: [bedDelegate.values objectAtIndex: [bedDelegate index]]];
_appDelegate.int_numBedV = [bedDelegate index];
break;
}
case 4:{
[tf_numBath setText: [bathDelegate.values objectAtIndex: [bathDelegate index]]];
_appDelegate.int_numBathV = [bathDelegate index];
break;
}
case 5:{
NSString * priceString = [[NSString alloc] initWithFormat:#"%# - %#",
[priceDelegate.values objectAtIndex: [priceDelegate index1]],
[priceDelegate.values2 objectAtIndex: [priceDelegate index2]]];
[tf_price setText:priceString];
_appDelegate.int_minPriceV = [priceDelegate index1];
_appDelegate.int_maxPriceV = [priceDelegate index2];
break;
}
case 6:{
[tf_currency setText: [currencyDelegate.values objectAtIndex: [currencyDelegate index]]];
_appDelegate.int_currencyV = [currencyDelegate index];
break;
}
}
[popoverController dismissPopoverAnimated:YES];
popoverController = nil;
[self dismissActionSheet];
}
My picker view
#import "PropertyTypeDelegate.h"
#implementation PropertyTypeDelegate
#synthesize values;
-(id)init{
self = [super init];
[self loadData];
return self;
}
-(int)index{ return index;}
-(void) loadData{
NSArray* array = [[NSArray alloc] initWithObjects:
NSLocalizedString(#"No Preference", nil),
NSLocalizedString(#"Villa", nil),
NSLocalizedString(#"Town House", nil),
NSLocalizedString(#"Apartment", nil),
NSLocalizedString(#"Retail", nil),
NSLocalizedString(#"Labour Camp", nil),
NSLocalizedString(#"Office", nil),
NSLocalizedString(#"Warehouse", nil),
NSLocalizedString(#"Land Residential", nil),
NSLocalizedString(#"Hotel apartment", nil),
NSLocalizedString(#"Residential Building", nil),
nil];
self.values = array;
index = 0;
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
return [values count];
}
-(NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent: (NSInteger)component{ return [values objectAtIndex:row];
}
-(void)pickerView:(UIPickerView *) thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
index = (int) (NSInteger)row;
}
#end
The link provided above actually refers to Apple Doc where it has removed adding subview to UIActionSheet. In your code, you are doing similar thing by adding UIPickerView into UIActionSheet. So in iOS8 onwards, even if the view is added to UIActionSheet, the view returned is actually nil while displaying.
For this purpose you can use ActionSheetPicker-3.0.
Actually, it's not UIActionSheet anymore. But looks exactly the same, and that's why it works on iOS8.
Do let me know if this answers your query!

Issue in previewing the video using AVFoundation and MPMovieController at a time in iphone sdk

I am Using AVFoundation's AVCaptureSession to capture the video and I am using the MPMoviePlayerController to play the streamed url(video) from server. When I am capturing only video with AVCaptureSession there is no problem. But When I tried to play the streamed url(with MPMoviePlayerController) along with capturing of video with AVCaptureSession at a time the problem occurs as the capturing from AVCaptureSession stops.
This is what I had done:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication ]delegate];
if([appDelegate isIpad] == YES)
controlsView = [[UIView alloc] initWithFrame:CGRectMake(self.view.bounds.origin.x+200, self.view.bounds.origin.y+250, self.view.bounds.size.width, self.view.bounds.size.height)];
else
controlsView = [[UIView alloc] initWithFrame:self.view.bounds];
controlsView.backgroundColor = [UIColor blackColor];
[self.view addSubview:controlsView];
[self.view sendSubviewToBack:controlsView];
//settingsBtn = [[UIButton alloc]initWithFrame:CGRectMake(10,400, 50, 50)];
settingsBtn = [[UIButton alloc]initWithFrame:CGRectMake(10,400, 50, 50)];
[settingsBtn setImage:[UIImage imageNamed:#"settings.png"] forState:UIControlStateNormal];
[settingsBtn addTarget:self action:#selector(settingsAction) forControlEvents:UIControlEventTouchUpInside];
[controlsView addSubview:settingsBtn];
callButton = [[UIButton alloc]initWithFrame:CGRectMake(260,400, 50, 50)];
if(isCallButtonClicked ==NO)
[callButton setImage:[UIImage imageNamed:#"call.png"] forState:UIControlStateNormal];
else
[callButton setImage:[UIImage imageNamed:#"callEnd.png"] forState:UIControlStateNormal];
[callButton addTarget:self action:#selector(callAction) forControlEvents:UIControlEventTouchUpInside];
[controlsView addSubview:callButton];
statusLabel = [[UILabel alloc]initWithFrame:CGRectMake(120, 20, 150, 40)];
statusLabel.textColor = [UIColor whiteColor];
statusLabel.backgroundColor = [UIColor clearColor];
statusLabel.textAlignment = UITextAlignmentLeft;
statusLabel.font = [UIFont boldSystemFontOfSize:20];
dot1 = [[UIView alloc] initWithFrame:CGRectMake(75, 20, 7, 7)];
dot1.layer.cornerRadius = 5;
dot1.backgroundColor = [UIColor whiteColor];
[statusLabel addSubview:dot1];
dot2 = [[UIView alloc] initWithFrame:CGRectMake(84, 20, 7, 7)];
dot2.layer.cornerRadius = 5;
dot2.backgroundColor = [UIColor whiteColor];
[statusLabel addSubview:dot2];
dot3 = [[UIView alloc] initWithFrame:CGRectMake(93, 20, 7, 7)];
dot3.layer.cornerRadius = 5;
dot3.backgroundColor = [UIColor whiteColor];
[statusLabel addSubview:dot3];
downStreamView = [[UIView alloc]initWithFrame:CGRectMake(controlsView.bounds.origin.x, controlsView.bounds.origin.y, controlsView.bounds.size.width, controlsView.bounds.size.height - 70)];
[[controlsView layer] addSublayer:downStreamView.layer];
downStreamView.layer.backgroundColor = [UIColor greenColor].CGColor;
AVCaptureSession *captureSession = [[AVCaptureSession alloc]init];
NSError *error;
/* getting the device input */
AVCaptureDeviceInput *videoInput = [AVCaptureDeviceInput deviceInputWithDevice:[self frontFacingCamera] error:&error];
if(error)
{
NSLog(#"%#",#"Could not create video input");
}
[captureSession addInput:videoInput];
AVCaptureDeviceInput *audioInput = [AVCaptureDeviceInput deviceInputWithDevice:[self audioDevice] error:&error];
[captureSession addInput:audioInput];
audioOutput = [[AVCaptureAudioDataOutput alloc]init];
[captureSession addOutput:audioOutput];
previewLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:captureSession];
[previewLayer setFrame:CGRectMake(controlsView.bounds.origin.x, controlsView.bounds.origin.y, controlsView.bounds.size.width, controlsView.bounds.size.height - 70)];
[previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[[controlsView layer] addSublayer:previewLayer];
[captureSession startRunning];
}
//make call Action
-(void)makeCallAction
{
if(isCallButtonClicked == NO)
{
statusLabel.text = #"Dialling";
[controlsView addSubview:statusLabel];
if(!isAnimationStarted)
[self animate];
[callButton setImage:[UIImage imageNamed:#"callEnd.png"] forState:UIControlStateNormal];
[UIView animateWithDuration:2.0
animations:^{
CGRect frame = CGRectMake(downStreamView.layer.bounds.origin.x, downStreamView.layer.bounds.size.height-100, 100, 100);
previewLayer.frame = frame;
[downStreamView.layer addSublayer:previewLayer];
}
completion:^(BOOL finished){
//Do nothing
}];
isCallButtonClicked = YES;
}
else if(isCallButtonClicked == YES)
{
[statusLabel removeFromSuperview];
[callButton setImage:[UIImage imageNamed:#"call.png"] forState:UIControlStateNormal];
[UIView animateWithDuration:2.0
animations:^{
[previewLayer setFrame:CGRectMake(controlsView.bounds.origin.x, controlsView.bounds.origin.y, controlsView.bounds.size.width, controlsView.bounds.size.height - 70)];
[[controlsView layer] addSublayer:previewLayer];
}
completion:^(BOOL finished){
//Do nothing
}];
isCallButtonClicked = NO;
}
}
//Settings Action
-(void)settingsAction
{
NSString *nibName = nil;
if ([[[UIDevice currentDevice] model] isEqualToString:#"iPhone"] || [[[UIDevice currentDevice] model] isEqualToString:#"iPhone Simulator"]) {
nibName = #"SettingsViewController";
}
else {
nibName = #"SettingsViewController_iPad";
}
SettingsViewController *settingsController = [[SettingsViewController alloc]initWithNibName:nibName bundle:nil];
[self.navigationController presentModalViewController:settingsController animated:YES];
}
-(void)callAction
{
NSURL *theMovieURL = [NSURL URLWithString:#"someURL.m3u8"];
if (theMovieURL)
{
if ([theMovieURL scheme]) // sanity check on the URL
{
/* Play the movie with the specified URL. */
[self playStreamingURL:theMovieURL];
}
}
[self makeCallAction];
}
-(void)playStreamingURL:(NSURL *)aUrlStr
{
MPMovieSourceType movieSourceType = MPMovieSourceTypeUnknown;
/* If we have a streaming url then specify the movie source type. */
if ([[aUrlStr pathExtension] compare:#"m3u8" options:NSCaseInsensitiveSearch] == NSOrderedSame)
{
movieSourceType = MPMovieSourceTypeStreaming;
}
[self createAndPlayMovieForURL:aUrlStr sourceType:movieSourceType];
}
-(void)createAndPlayMovieForURL:(NSURL *)movieURL sourceType:(MPMovieSourceType)sourceType
{
[self createAndConfigurePlayerWithURL:movieURL sourceType:sourceType];
/* making the player to be visible in full screen mode */
//if(!self.moviePlayerController.fullscreen)
// self.moviePlayerController.fullscreen = YES;
/* disabling the controls of the movie player */
self.moviePlayerController.controlStyle = MPMovieControlStyleNone;
/* Play the movie! */
[[self moviePlayerController] play];
}
-(void)createAndConfigurePlayerWithURL:(NSURL *)movieURL sourceType:(MPMovieSourceType)sourceType
{
[controlsView addSubview:downStreamView];
/* Create a new movie player object. */
MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
if (player)
{
/* Save the movie object. */
[self setMoviePlayerController:player];
player.contentURL = MPMovieControlStyleNone;
//if(!player.fullscreen)
// player.fullscreen = YES;
/* Register the current object as an observer for the movie
notifications. */
// [self installMovieNotificationObservers];
/* Specify the URL that points to the movie file. */
[player setContentURL:movieURL];
/* If you specify the movie type before playing the movie it can result
in faster load times. */
[player setMovieSourceType:sourceType];
/* Apply the user movie preference settings to the movie player object. */
//[self applyUserSettingsToMoviePlayer];
/* Add a background view as a subview to hide our other view controls
underneath during movie playback. */
//CGRect viewInsetRect = CGRectInset ([self.view bounds],
// kMovieViewOffsetX,
//kMovieViewOffsetY );
/* Inset the movie frame in the parent view frame. */
[[player view] setFrame:downStreamView.bounds];
[player view].backgroundColor = [UIColor redColor];
/* To present a movie in your application, incorporate the view contained
in a movie player’s view property into your application’s view hierarchy.
Be sure to size the frame correctly. */
[downStreamView.layer addSublayer: [player view].layer];
}
}
-(void)installMovieNotificationObservers
{
MPMoviePlayerController *player = [self moviePlayerController];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(loadStateDidChange:)
name:MPMoviePlayerLoadStateDidChangeNotification
object:player];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlayBackDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:player];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(mediaIsPreparedToPlayDidChange:)
name:MPMediaPlaybackIsPreparedToPlayDidChangeNotification
object:player];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlayBackStateDidChange:)
name:MPMoviePlayerPlaybackStateDidChangeNotification
object:player];
}
/* Notification called when the movie finished playing. */
- (void) moviePlayBackDidFinish:(NSNotification*)notification
{
NSNumber *reason = [[notification userInfo] objectForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey];
switch ([reason integerValue])
{
/* The end of the movie was reached. */
case MPMovieFinishReasonPlaybackEnded:
/*
Add your code here to handle MPMovieFinishReasonPlaybackEnded.
*/
break;
/* An error was encountered during playback. */
case MPMovieFinishReasonPlaybackError:
NSLog(#"An error was encountered during playback");
[self performSelectorOnMainThread:#selector(displayError:) withObject:[[notification userInfo] objectForKey:#"error"] waitUntilDone:NO];
[self removeMovieViewFromViewHierarchy];
break;
/* The user stopped playback. */
case MPMovieFinishReasonUserExited:
[self removeMovieViewFromViewHierarchy];
break;
default:
break;
}
}
/* Remove the movie view from the view hierarchy. */
-(void)removeMovieViewFromViewHierarchy
{
MPMoviePlayerController *player = [self moviePlayerController];
[player.view removeFromSuperview];
}
- (void)animate {
isAnimationStarted = YES;
//First Animation
[UIView animateWithDuration:0.5 animations:^{
dot1.alpha = 1;
dot2.alpha = 0.5;
dot3.alpha = 0.5;
} completion:^(BOOL finished) {
//2nd Animation
[UIView animateWithDuration:0.5 animations:^{
dot1.alpha = 0.5;
dot2.alpha = 1;
dot3.alpha = 0.5;
} completion:^(BOOL finished) {
//3rd Animation
[UIView animateWithDuration:0.5 animations:^{
dot1.alpha = 0.5;
dot2.alpha = 0.5;
dot3.alpha = 1;
} completion:^(BOOL finished) {
[self performSelector:#selector(animate)];
}];
}];
}];
}
// Find a camera with the specificed AVCaptureDevicePosition, returning nil if one is not found
- (AVCaptureDevice *) cameraWithPosition:(AVCaptureDevicePosition) position
{
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for (AVCaptureDevice *device in devices) {
if ([device position] == position) {
return device;
}
}
return nil;
}
// Find a front facing camera, returning nil if one is not found
- (AVCaptureDevice *) frontFacingCamera
{
return [self cameraWithPosition:AVCaptureDevicePositionFront];
}
// Find a back facing camera, returning nil if one is not found
- (AVCaptureDevice *) backFacingCamera
{
return [self cameraWithPosition:AVCaptureDevicePositionBack];
}
- (AVCaptureDevice *) audioDevice
{
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
if ([devices count] > 0) {
return [devices objectAtIndex:0];
}
return nil;
}
-(void)audioData:(id)info
{
NSArray *connections = audioOutput.connections;
AVCaptureConnection *connection = [connections objectAtIndex:0];
NSArray *audioChannels = connection.audioChannels;
AVCaptureAudioChannel *audioChannel = [audioChannels objectAtIndex:0];
//[label setText:[NSString stringWithFormat:#"%f", audioChannel.averagePowerLevel]];
}
Guy's Please help me how to resolve this issue :(
Regards

UITextField rightView "WhileEditing" problem

I try to subclass UITextField as follows to implement custom rightView as a Clear button:
-(void) drawRect:(CGRect)rect
{
[self.layer setBackgroundColor:[[UIColor colorWithRed:20.0/255.0 green:20.0/255.0 blue:20.0/255.0 alpha:1] CGColor]];
[self.layer setCornerRadius:15.0];
UIImage *imgClear = [UIImage imageNamed:#"btnClear"];
CGSize iSize = [imgClear size];
UIButton *clearButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, iSize.width, iSize.height)];
[clearButton setImage:imgClear forState:UIControlStateNormal];
[clearButton addTarget:self action:#selector(clearText:) forControlEvents:UIControlEventTouchUpInside];
[self setRightViewMode:UITextFieldViewModeWhileEditing];
[self setRightView:clearButton];
[clearButton release];
}
but the Problem is: when the textfield just becomes focus, "clear"-button becomes visible too and after i begin to tap the keyboard it dissapears. Any ideas?
I meet the same problem, too. I guess this is an iOS bug, however, I tried to fix this problem by following implementations and it works fine for me. Hope this will help you.
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
...
[self addTarget:self action:#selector(onEditing:) forControlEvents: UIControlEventEditingChanged]
...
}
-(void) onEditing:(id)sender {
if(![self.text isEqualToString:#""]){
self.rightViewMode = UITextFieldViewModeAlways;
}else{
self.rightViewMode = UITextFieldViewModeNever;
}
}
- (BOOL)becomeFirstResponder{
BOOL ret = YES ;
ret = [super becomeFirstResponder] ;
if( ret & ![self.text isEqualToString:#""]){
self.rightViewMode = UITextFieldViewModeAlways;
}else{
self.rightViewMode = UITextFieldViewModeNever;
}
return ret ;
}
- (BOOL)resignFirstResponder
{
BOOL ret = YES ;
ret = [super resignFirstResponder] ;
if( ret )
self.rightViewMode = UITextFieldViewModeNever;
return ret ;
}
- (void) clearText:(id)sender
{
self.text = #"";
self.rightViewMode = UITextFieldViewModeNever;
}
You shoud use : [self setRightViewMode:UITextFieldViewModeAlways];
Subclass UITextField and override -layoutSubviews.
- (void)layoutSubviews
{
[super layoutSubviews];
// HACK: There is an iOS bug where the right view is not displayed when there is text in the text field. Also, iOS adds and removes the rightView. This code adds the right view and uses hide-unhide instead.
UIView *rightView = [self rightView];
if (rightView != nil && [self clearButtonMode] == UITextFieldViewModeNever) {
BOOL showRightView;
BOOL isFirstResponder = [self isFirstResponder];
switch ([self rightViewMode]) {
case UITextFieldViewModeNever:
showRightView = FALSE;
break;
case UITextFieldViewModeWhileEditing:
showRightView = isFirstResponder;
break;
case UITextFieldViewModeUnlessEditing:
showRightView = !isFirstResponder;
break;
case UITextFieldViewModeAlways:
default:
showRightView = TRUE;
break;
}
showRightView = (showRightView && ![[self text] isEqualToString:#""]);
[rightView setFrame:[self rightViewRectForBounds:[self bounds]]];
[rightView setHidden:!showRightView];
[self addSubview:rightView];
}
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
UITextField *searchField = nil;
for (UIView *subview in controller.searchBar.subviews) {
DebugLog(#"%#",[subview description]);
if ([subview isKindOfClass:[UITextField class]]) {
searchField = (UITextField *)subview;
UIImageView *clearIconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"ClearIcon.png"]];
searchField.rightView = clearIconView;
searchField.rightViewMode = UITextFieldViewModeAlways;
[clearIconView release];
break;
}
}
}
Simple code for solve this problem
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
textField.rightViewMode=UITextFieldViewModeAlways;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
textField.rightViewMode=UITextFieldViewModeNever;
return YES;
}
I have written an open source class, STAResizingTextField, that allows you to specify custom clear text field button images.

Implementing toggle feature in a UIButton

I want to know how to add the toggling feature to a UIButton, something like the user taps a unselected button the button becomes selected and stays selected till the user taps it again there by making unselected like it was before.
I was thinking of making an IBAction which changes it from unselected to selected, how can I do that?
Heres what I tried:
-(IBAction)toggle {
//Toggle on implementation.
button.selected = YES;
button.highlighted = NO;
button.enabled = YES;
//Toggle off implementation.
if (button.highlighted == YES) {
button.selected = NO;
button.highlighted = YES;
button.enabled = NO;
}
}
Problem...
-(IBAction)toggleFav {
if (favButton == nil) {
UIImage *unselectedImage = [UIImage imageNamed:#"favUntapped.png"];
UIImage *selectedImage = [UIImage imageNamed:#"favTapped.png"];
[favButton setImage:unselectedImage forState:UIControlStateNormal];
[favButton setImage:selectedImage forState:UIControlStateSelected];
[favButton setFrame:CGRectMake(0, 0, 40, 40)];
}
if([favButton isSelected]){
//Add to menu.
[favButton setSelected:NO];
} else {
//Remove from menu.
[favButton setSelected:YES];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
UIImage *unselectedImage = [UIImage imageNamed:#"unselected.png"];
UIImage *selectedImage = [UIImage imageNamed:#"selected.png"];
UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom];
[b setBackgroundImage:unselectedImage forState:UIControlStateNormal];
[b setBackgroundImage:selectedImage forState:UIControlStateSelected];
[b addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[b setFrame:CGRectMake(0, 0, 40, 40)];
[cell.contentView addSubview:b];
}
return cell;
}
-(void) buttonPressed:(UIButton *)sender
{
if([sender isSelected]){
//...
[sender setSelected:NO];
} else {
//...
[sender setSelected:YES];
}
}
Your toggleFav code doesn't make much sense.
if (favButton == nil) { checks, if favButton is present. But if you are wiring it up with IB, it should always been there at that point. And if it wasn't how could the button call this method? So do it like this:
-(void)viewDidLoad
{
//....
UIImage *unselectedImage = [UIImage imageNamed:#"favUntapped.png"];
UIImage *selectedImage = [UIImage imageNamed:#"favTapped.png"];
[favButton setImage:unselectedImage forState:UIControlStateNormal];
[favButton setImage:selectedImage forState:UIControlStateSelected];
[favButton setFrame:CGRectMake(0, 0, 40, 40)];
//....
}
-(IBAction)toggleFav:(UIButton *)sender {
if([sender isSelected]){
//...
[sender setSelected:NO];
} else {
//...
[sender setSelected:YES];
}
}
Here you'll find an example project, with a DetaiView, that holds a Button with the 2 states.
Note: I am saving the information of what button was selected in the NSUserDefaults. You should not do that. Instead you'll want to save it in the model. But as I dont have informations on your model, I am just using NSUserDefaults.
-(void)hitButton:(UIButton*)button
{
buttonOnFlag = !buttonOnFlag;
if( buttonFlag )
[self performSelector:#selector(setHighlight:) withObject:button afterDelay:0];
}
- (void)setHighlight:(UIButton*)button
{
button.highlighted = true;
}
Use button.highlighted property
You should code like this:
-(IBAction)toggle:(id)sender {
//Toggle on implementation.
if (sender.highlighted == NO)
{
sender.selected = YES;
sender.highlighted = NO;
sender.enabled = YES;
}
//Toggle off implementation.
else{
sender.selected = NO;
sender.highlighted = YES;
sender.enabled = NO;
}
}