I've finally got two pickers into one viewcontroller and i've realised they're a little tricky to see because the background is dark. How do I go about changing the colour of the pickers text?
Here's my whole view controller M
//
// ViewController.m
// Repayment Calculator
//
// Created by Stewart Piper-Smith on 04/11/2015.
// Copyright (c) 2015 Stewart Piper-Smith. All rights reserved.
//
#import "ViewController.h"
#interface ViewController ()
#end
NSArray *_pickerViewArray;
NSArray *CareerViewArray;
#implementation ViewController
#synthesize button1, textbox1, textbox2, textbox3, startingsalary, repaymentlabel, debtlabel, startingrepayments, timetakentopayoffloan, realtimetakentopayoffloan, debtamounttextfield, annualrepaymentstextfield, monthlyrepaymentstextfield,weeklyrepaymentstextfield, payoffloantextfield, testlabel, annualrepaymentstest, totaldebtamounttest, writtenofflabel,payoffloanlabel,newlabel;
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
// - (IBAction)button1Press:(id)sender {
// [button1 setTitle:textbox1.text forState:UIControlStateNormal];
// }
//The start of the calculate button that starts the calculations.
-(IBAction)menucontactbuttonPress:(id)sender {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"Error"
message:#"Contact Form Coming Soon"
preferredStyle:UIAlertControllerStyleAlert];
//We add buttons to the alert controller by creating UIAlertActions:
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:#"Ok"
style:UIAlertActionStyleDefault
handler:nil]; //You can use a block here to handle a press on this button
[alertController addAction:actionOk];
[self presentViewController:alertController animated:YES completion:nil];
}
-(IBAction)button1Press:(id)sender
{
[self.view endEditing:YES];
int x = ([textbox1.text intValue]);
int y = ([textbox2.text intValue]);
int q = ([textbox3.text intValue]);
float startingsal = ([startingsalary.text intValue]);
int debtamounttfield = ([debtamounttextfield.text intValue]);
float annualrepayments = ([annualrepaymentstextfield.text floatValue]);
//PROBLEM STARTS
float p1 = debtamounttfield /annualrepayments;//([debtamounttextfield.text intValue]);
if(isnan(p1) || isinf(p1)){
p1 = 0.00;
}
//int a = ([annualrepaymentstextfield.text intValue]);
//int b = ([debtamounttextfield.text intValue]);
//[newlabel setText:[NSString stringWithFormat:#"%#", a/b]];
[testlabel setText:[NSString stringWithFormat:#"%.01f",p1]];
[totaldebtamounttest setText:[NSString stringWithFormat:#"%d", debtamounttfield]];
[annualrepaymentstest setText:[NSString stringWithFormat:#"%#", annualrepaymentstextfield]];
[payoffloantextfield setText:[NSString stringWithFormat:#"%.01f", p1]];
//PROBLEM ENDS
[debtamounttextfield setText:[NSString stringWithFormat:#"£" "%i" , (x + y) * q]];
int arp = (startingsal - 17335)*0.09;
[annualrepaymentstextfield setText:[NSString stringWithFormat:#"£" "%i", arp ]];
if (arp < 0) {
annualrepaymentstextfield.text = #"Written Off";
}
int monthlyrepayments = (startingsal - 17335)*0.09/12;
[monthlyrepaymentstextfield setText:[NSString stringWithFormat:#"£" "%i", monthlyrepayments]];
if (monthlyrepayments < 0){
monthlyrepaymentstextfield.text = #"Written Off";
}
int weeklyrepayments = (startingsal - 17335)*0.09/12/4;
[weeklyrepaymentstextfield setText:[NSString stringWithFormat:#"£" "%i", weeklyrepayments]];
if (weeklyrepayments < 0){
weeklyrepaymentstextfield.text = #"Written Off";
}
//Error Handling
//Enter starting salary
if ([annualrepaymentstextfield.text isEqualToString: #"Written Off"]) {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"Debt Written Off"
message:#"As it will take you longer than 30 years to pay off the loan, the debt would be written off."
preferredStyle:UIAlertControllerStyleAlert];
//We add buttons to the alert controller by creating UIAlertActions:
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:#"Ok"
style:UIAlertActionStyleDefault
handler:nil]; //You can use a block here to handle a press on this button
[alertController addAction:actionOk];
[self presentViewController:alertController animated:YES completion:nil];
}
if ([startingsalary.text isEqualToString: #""]) {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"Error"
message:#"Please enter your expected starting salary"
preferredStyle:UIAlertControllerStyleAlert];
//We add buttons to the alert controller by creating UIAlertActions:
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:#"Ok"
style:UIAlertActionStyleDefault
handler:nil]; //You can use a block here to handle a press on this button
[alertController addAction:actionOk];
[self presentViewController:alertController animated:YES completion:nil];
}
//If course length is equal to 0
if ([textbox3.text isEqualToString: #"0"]) {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"Error"
message:#"Your course lenth cannot be 0 Years. Please enter a different value"
preferredStyle:UIAlertControllerStyleAlert];
//We add buttons to the alert controller by creating UIAlertActions:
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:#"Ok"
style:UIAlertActionStyleDefault
handler:nil]; //You can use a block here to handle a press on this button
[alertController addAction:actionOk];
[self presentViewController:alertController animated:YES completion:nil];
}
//If course length text field is empty
if ([textbox3.text isEqualToString: #""]){
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"Error"
message:#"Please enter your current course length"
preferredStyle:UIAlertControllerStyleAlert];
//We add buttons to the alert controller by creating UIAlertActions:
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:#"Ok"
style:UIAlertActionStyleDefault
handler:nil]; //You can use a block here to handle a press on this button
[alertController addAction:actionOk];
[self presentViewController:alertController animated:YES completion:nil];
}
//time taken to pay off loan > 20 years
int newtimetaken = [timetakentopayoffloan.text intValue];
if (newtimetaken <= 20) {
writtenofflabel.text = #"WO";
}
}
-(IBAction)clearbutton:(id)sender {
[textbox1 setText:[NSString stringWithFormat:#""]];
[textbox2 setText:[NSString stringWithFormat:#""]];
[textbox3 setText:[NSString stringWithFormat:#""]];
[startingrepayments setText:[NSString stringWithFormat:#"Loan at start of repayments: "]];
[startingsalary setText:[NSString stringWithFormat:#""]];
[realtimetakentopayoffloan setText:[NSString stringWithFormat:#""]];
[debtamounttextfield setText:[NSString stringWithFormat:#""]];
[annualrepaymentstextfield setText:[NSString stringWithFormat:#""]];
[monthlyrepaymentstextfield setText:[NSString stringWithFormat:#""]];
[weeklyrepaymentstextfield setText:[NSString stringWithFormat:#""]];
[payoffloantextfield setText:[NSString stringWithFormat:#""]];
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"Cleared"
message:#"All fields have now been cleared."
preferredStyle:UIAlertControllerStyleAlert];
//We add buttons to the alert controller by creating UIAlertActions:
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:#"Ok"
style:UIAlertActionStyleDefault
handler:nil]; //You can use a block here to handle a press on this button
[alertController addAction:actionOk];
[self presentViewController:alertController animated:YES completion:nil];
}
- (void)viewDidLoad {
[super viewDidLoad];
myLabel.text = #"Use the scroller above...";
datePickerView.delegate = self;
//CareerPickerView.dataSource = self;
_pickerViewArray = #[#"Before September 2012",#"After September 2012"];
CareerViewArray = #[#"1000",#"2000"];
CareerPickerView.delegate = self;
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
if(pickerView == datePickerView)
{
NSString *dateSelected = [_pickerViewArray objectAtIndex:row];
myLabel.text = dateSelected;
}
else if(pickerView == CareerPickerView)
{
NSString *careerSelected = [CareerViewArray objectAtIndex:row];
startingsalary.text = careerSelected;
}
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
if(pickerView == datePickerView)
{
return _pickerViewArray.count;
}
else if(pickerView == CareerPickerView)
{
return CareerViewArray.count;
}
return 1;
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
-(NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
if(pickerView == datePickerView)
{
return _pickerViewArray[row];
}
else if(pickerView == CareerPickerView)
{
return CareerViewArray[row];
}
return nil;
}
#end
You might require to implement UIPickerViewDelegate method -pickerView:attributedTitleForRow:forComponent:
- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component
{
NSString *myTitle = #"my title";
NSAttributedString *myAttString = [[NSAttributedString alloc] initWithString:myTitle attributes:#{NSForegroundColorAttributeName:[UIColor whiteColor]}];
return myAttString;
}
Reference: iOS Documentation
Hope this helps.
you can use UIPickerView delegate method:
- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component
{
NSString *title = self.pickerArray[row];
NSAttributedString *attString = [[NSAttributedString alloc] initWithString:title attributes:#{NSForegroundColorAttributeName:NEON_GREEN}];
return attString;
}
Related
Any one know how to reload collectionView in parentViewController when removing childViewController.
Here, I am processing on click of button adding childViewController and on click of that childViewController I am getting data and that data will transferred to parentViewController after that child view get's remove from parentViewController.
I am getting data from childViewController, also reloading collection view.
dispatch_async(dispatch_get_main_queue(),^{
[self.view layoutIfNeeded];
[self.collectionViewcellItem layoutIfNeeded];
[self.collectionViewcellItem reloadData];
});
but, no effect of reloading here seen.
means not able to change parentviewconroller view after removal of childViewController.
Thank you
Waiting for the answer and yes I am doing it in objective c.
parentViewController file.
[self.view addSubview:filterMenuVC.view];
filterMenuVC.view.backgroundColor = [UIColor clearColor];
[self addChildViewController:filterMenuVC];
[self.view addSubview:filterMenuVC.view];
[self animationSideFilterMenuBarOpen];
[filterMenuVC didMoveToParentViewController:self];
childViewController file
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"%#",[NSString stringWithFormat:#"%ld",(long)indexPath.row]);
// // [wel animationSideFilterMenuBarClose];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
int categoryId = (int)cell.textLabel.tag;
[self animationSideMainMenuBarClose:categoryId];
}
-(void)animationSideMainMenuBarClose:(int)categoryId{
CGFloat width = [UIScreen mainScreen].bounds.size.width;
self.view.frame = CGRectMake(width - self.view.frame.size.width, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height);
[UIView animateWithDuration:0.5 animations:^{
self.view.frame = CGRectMake(width, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height);
}
completion:^(BOOL finished){
[self.view removeFromSuperview];
self.view = nil;
NSLog(#"category id Filter: %d",categoryId);
BOOL boolresponse = [wel getUserWork:categoryId];
if (boolresponse == NO) {
UIAlertController * alert = [UIAlertController
alertControllerWithTitle:#""
message:#"No internet connection"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okButton = [UIAlertAction
actionWithTitle:#"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
}];
[alert addAction:okButton];
[self presentViewController:alert animated:YES completion:nil];
}
}];
}
here, BOOL boolresponse = [wel getUserWork:categoryId]; getUserWork is the function in parentViewController, I call that and removing the childViewController. get correct data but not able to reload collectionView.
parentViewFunction which I am calling.
-(BOOL)getUserWork:(int)catergoryId{
appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
[self dismissViewControllerAnimated:true completion:^{
//do whatever you do here
[self.collectionViewcellItem reloadData];
}];
categoryIdStart = catergoryId;
Reachability *r = [[Reachability alloc]init];
if(r.currentReachabilityStatus != NotReachable) {
return NO;
}
else
{
[SVProgressHUD show];
[SVProgressHUD setStatus:#"Loading..."];
[SVProgressHUD setRingRadius:20];
[SVProgressHUD setRingThickness:10];
[SVProgressHUD setBorderColor:[UIColor orangeColor]];
[SVProgressHUD setBorderWidth:0.5];
[SVProgressHUD setForegroundColor:[UIColor orangeColor]];
NSLog(#"id category: %d",categoryIdStart);
NSDictionary *params = [[NSDictionary alloc] initWithObjectsAndKeys:[appDelegate.UserDic valueForKey:#"token"],#"token",[appDelegate.UserDic valueForKey:#"id"],#"id_user",[NSString stringWithFormat:#"%d",categoryIdStart],#"id_category",nil];
NSMutableArray *postArray = [NSMutableArray array];
[params enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) {
[postArray addObject:[NSString stringWithFormat:#"%#=%#", key, [apiCall percentEscapeString:obj]]];
}];
NSString *postString = [postArray componentsJoinedByString:#"&"];
[apiCall apiType:#"xyzzy" pD:postString dataRetrive:^(NSDictionary *dictionary){
int status = [[dictionary valueForKey:#"status"] intValue];
if (status == 0) {
[SVProgressHUD dismiss];
dispatch_async(dispatch_get_main_queue(),^{
UIAlertController * alert = [UIAlertController
alertControllerWithTitle:#""
message:[dictionary valueForKey:#"msg"]
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okButton = [UIAlertAction
actionWithTitle:#"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
}];
[alert addAction:okButton];
[self presentViewController:alert animated:YES completion:nil];
});
}
else{
[SVProgressHUD dismiss];
[cacheImage removeAllObjects];
dic = [dictionary valueForKey:#"data"];
NSLog(#"Category detail: %# %lu",dic,(unsigned long)dic.count);
NSLog(#"image category %# :",[dic valueForKey:#"category_name"]);
dispatch_async(dispatch_get_main_queue(),^{
[self.view layoutIfNeeded];
[self.collectionViewcellItem layoutIfNeeded];
[self.collectionViewcellItem reloadData];
[self viewWillAppear:true];
});
}
}];
return YES;
}
}
I am trying to fix on iOS 7+ an alert allowing me to input a 4 digit code, at the moment, the prompt appears, but the input field is blank and does not allow me to put anything in.
The methods below are used to call the pin code option, starting with the segmentedAction as seen below;
-(void)segmentedAction:(id)sender{
UISegmentedControl *control = (UISegmentedControl *)sender;
NSString *pincode = [self.objSettingAdapter getPinCode];
NSString *patternCode = [self.objSettingAdapter getPatternCode];
NSInteger pincodetype = control.selectedSegmentIndex;
if ((![pincode length]>0) && pincodetype==0) {
[self takePinInputFromUser:#"Choose Your PIN Code"];
}else if((![patternCode length]>0) && pincodetype==1) {
[self takePatterInputFromUser:#"Draw Pattern"];
}else {
[self.objSettingAdapter setPinCodeType:control.selectedSegmentIndex];
}
}
-(void)buttonAction:(id)sender{
UIButton *btn = (UIButton *)sender;
NSString *pincode = [self.objSettingAdapter getPinCode];
NSString *patternCode = [self.objSettingAdapter getPatternCode];
if ([btn.titleLabel.text isEqualToString:#"Reset PIN"] && (![pincode length]>0)) {
[self takePinInputFromUser:#"Choose Your PIN Code"];
}else if ([btn.titleLabel.text isEqualToString:#"Reset Pattern"] && (![patternCode length]>0)) {
[self takePatterInputFromUser:#"Draw Pattern"];
}else {
[self.objSettingAdapter setPinCodeType:([btn.titleLabel.text isEqualToString:#"Reset PIN"] ? 0 : 1)];
}
}
-(void)takePinInputFromUser:(NSString *)title{
AlertPinCode *prompt = [AlertPinCode alloc];
prompt = [prompt initWithTitle:title message:#"\n\n" delegate:self cancelButtonTitle:#"Cancel" okButtonTitle:#"Done"];
[prompt show];
}
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
AlertPinCode *alertPin = (AlertPinCode *) alertView;
if (buttonIndex != [alertView cancelButtonIndex])
{
NSString *userPin = [alertPin enteredText];
if ([userPin length]<4) {
[alertPin dismissWithClickedButtonIndex:0 animated:YES];
[self takePinInputFromUser:#"Chose 4 Digit PIN Code"];
}else {
[self.objSettingAdapter setPinCodeType:0];
[self.objSettingAdapter setPinCode:userPin];
}
}
}
Try the following.
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"Title" message:nil preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:#"Cancel" style:UIAlertActionStyleCancel handler:nil];
__weak typeof(UIAlertController) *weakAlertController = alertController;
UIAlertAction *okAction = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
__strong typeof(UIAlertController) *strongAlertController = weakAlertController;
UITextField *digitTextField = [strongAlertController.textFields firstObject];
NSString *pinCode = digitTextField.text;
NSLog(#"pin code: %#", pinCode);
// Do something with the PIN code
}];
[alertController addAction:cancelAction];
[alertController addAction:okAction];
[alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
textField.placeholder = #"Input 4 Digit PIN Code";
}];
[self presentViewController:alertController animated:YES completion:nil];
you can use UIAlertViewController
I am creating login screen using Objective C in which i want to implement validation for User name(E-Mail) and password.How to implement this in very simple way.
You can always make use textField shouldChangeCharactersInRange delegate to handle the number of characters allowed in textField. Have look at the solution provided below :) Hope it helps
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if(textField == self.emailTextField){
if (textField.text.length < 30 || string.length == 0){
return YES;
}
else{
return NO;
}
}
}
EDIT
As per your comments you are not recieveing the textField delegates, so here is what you can do :)
In your ViewController, confirm the UITextFieldDelegate using,
YourViewController : UIViewController <UITextFieldDelegate>
In your viewDidLoad or ViewWillAppear set the textField delegate as self.
self.emailTextField.delegate = self;
If you click the Validate Button, set the validate button Action and see the below code,first check the two textfield empty or not, if you give text then again check its valid email type or not, then all conditions are true, then put your code and run,
-(IBAction)action:(id)sender
{
if (tfMail.text.length == 0 || tfPass.text.length == 0)
{
[self validatetextfield];
}
else if (![tfMail.text isEqualToString:#""])
{
NSString *emailRegEx = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegEx];
//Valid email address
if ([emailTest evaluateWithObject:tfMail.text] == YES)
{
//Its validated put your success code,
}
else
{
UIAlertController *aler = [UIAlertController alertControllerWithTitle:#"Test!" message:#"Please Enter Valid Email Address. \nex. fdsjfkd#mail.com" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[self dismissViewControllerAnimated:YES completion:nil];
}];
[aler addAction:action];
[self presentViewController:aler animated:YES completion:nil];
//not valid email address
}
}
}
Alert Message Method:
-(void) validatetextfield
{
if (tfMail.text.length==0) {
UIAlertController *aler = [UIAlertController alertControllerWithTitle:#"Email Field Empty!" message:#"Please Enter the Email" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[self dismissViewControllerAnimated:YES completion:nil];
}];
[aler addAction:action];
[self presentViewController:aler animated:YES completion:nil];
[tfMail becomeFirstResponder];
}
else if (tfPass.text.length==0)
{
UIAlertController *aler = [UIAlertController alertControllerWithTitle:#"Password Field Empty!" message:#"Please Enter the Password" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[self dismissViewControllerAnimated:YES completion:nil];
}];
[aler addAction:action];
[self presentViewController:aler animated:YES completion:nil];
[tfPass becomeFirstResponder];
}
}
its successfully working for me, hope its helpful.
I'm using UIAlertController for the first time. I need to prompt the user for an input. Anyway, the following is what I have.
- (void)showAlert {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:#"Hello!" message:#"Type something.") preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *noButton = [UIAlertAction actionWithTitle:#"Cancel") style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
}];
UIAlertAction *yesButton = [UIAlertAction actionWithTitle:#"Enter") style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//NSString *input = alert.textFields[0].text;
//NSLog(#"input was '%#'", input);
UITextField *textField = alert.textFields[0];
NSLog(#"%#",textField.text); // <====== It's not returned
}];
[alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
[textField addTarget:self action:#selector(alertTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
[yesButton setEnabled:NO];
}];
[alert addAction:noButton];
[alert addAction:yesButton];
[self presentViewController:alert animated:YES completion:nil];
}
- (void)alertTextFieldDidChange:(UITextField *)sender {
UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
if (alertController) {
UITextField *textfield = alertController.textFields.firstObject;
UIAlertAction *okAction = alertController.actions.lastObject;
okAction.enabled = [self validateName2:textfield.text:5]; // function for validating user input
}
}
For some reason, when the user tap Yes, the application doesn't return user input. In fact, Xcode dashes 'text' as in 'NSString *input = alert.textFields[0].text. A strange thing is that UIAlertView doesn't return user input. That's why I've switched to UIAlertController.
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
if ([alertView tag] == 101) {
if (buttonIndex == 1) {
NSString *username = [[alertView textFieldAtIndex:0] text];
NSLog(#"%#",username); // <====== It's never returned.
}
}
}
Anyway, I wonder what I'm doing wrong with UIAlertController?
Muchos thankos
p.s. I'm using Xcode 6.4 (6E35b). This issue may be caused by Xcode. If I debug the code with the iPad2 simulator, it'll actually return user input while it doesn't if I use the iPhone4S simulator.
Use this for textField in alertcontroller
__block typeof(self) weakSelf = self;
UIAlertController *alertController;
alertController = [UIAlertController alertControllerWithTitle:title
message:message
preferredStyle:UIAlertControllerStyleAlert];
[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField)
{
textField.tag = 1001;
textField.delegate = weakSelf;
textField.placeholder = #"";
[textField addTarget:weakSelf action:#selector(alertTextFieldDidChange:)
forControlEvents:UIControlEventEditingChanged];
}];
//OK Button
UIAlertAction *okAction = [UIAlertAction
actionWithTitle:#"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action)
{
UITextField *textField = alertController.textFields.firstObject;
// Do stuff here
}];
[alertController addAction:okAction];
[self presentViewController:alertController animated:YES completion:nil];
- (void)alertTextFieldDidChange:(UITextField *)sender
{
alertController = (UIAlertController *)self.presentedViewController;
if (alertController)
{
UITextField *textField = alertController.textFields.firstObject;
UIAlertAction *okAction = alertController.actions.lastObject;
okAction.enabled = textField.text.length > 0; // condition to enable button
}
}
#pragma mark - UITextField delegate methods
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
I would recommend using UITextFieldDelegate to handle the textField!
Set textField.delegate = self and then use the - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string method to do what you do in alertTextFieldDidChange if the replacementString has a length of > 0.
You are provided with delegate methods for UITextField so you don't have to create the selectors yourself, I recommend you use them to their fullest!
Here are the docs in case you want to know more! https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITextFieldDelegate_Protocol/
instead of a button i'd like to change the view controller if a alert is validated but i've no idea how to do is. I use a cocoa pod for the notification (just cause the design is beautiful). every answer is welcome!
- (IBAction)changeTheme:(UIButton *)sender {
// for changing view controller
[UIView animateKeyframesWithDuration:1.0 delay:0 options:0 animations:^{
changeTheme.transform = CGAffineTransformMakeScale(2, 2);
} completion:^(BOOL finished) {
// init alert with options
SCLAlertView *changeThemeNotification = [[SCLAlertView alloc] init];
// to sport
[changeThemeNotification addButton:#"change to sport" validationBlock:^BOOL{
BOOL passedValidation = true;
return passedValidation;
} actionBlock:^{
}];
// to food
[changeThemeNotification addButton:#"change to food" validationBlock:^BOOL{
BOOL passedValidation = true;
return passedValidation;
} actionBlock:^{
[self.view setBackgroundColor:[UIColor blackColor]];
}];
// to animal
[changeThemeNotification addButton:#"change to animal" validationBlock:^BOOL{
BOOL passedValidation = true;
return passedValidation;
} actionBlock:^{
[self.view setBackgroundColor:[UIColor greenColor]];
}];
// else (message & options)
[changeThemeNotification showCustom:self image:nil color:[self.colorWheel randomColor] title:#"Test" subTitle:#"This is a test notification for the navigation." closeButtonTitle:#"stay" duration:0.0f];
changeThemeNotification.hideAnimationType = SlideOutToBottom;
changeThemeNotification.shouldDismissOnTapOutside = YES;
changeThemeNotification.soundURL = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/url_to_sound.mp3", [[NSBundle mainBundle] resourcePath]]];
}];
}
try this
SCLAlertView *changeThemeNotification = [[SCLAlertView alloc] init];
[changeThemeNotification addButton:#"change to sport" validationBlock:^BOOL{
BOOL passedValidation = true;
return passedValidation;
} actionBlock:^{
[self performSegueWithIdentifier:#"yourSegueName" sender:self];
}];
The following code will help:
To check the iOS version:
#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
To display the alert view:
if(SYSTEM_VERSION_LESS_THAN(#"8.0"))
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#""
message:#"your message"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"OK", nil];
[alert show];
}
else
{
UIAlertController *alertController = [UIAlertController
alertControllerWithTitle:#""
message:#"You message..."
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction
actionWithTitle:NSLocalizedString(#"OK", #"OK action")
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action)
{
[self performSegueWithIdentifier:#"yourSegueName" sender:self];
}];
[alertController addAction:okAction];
[self presentViewController:alertController animated:YES completion:nil];
}
Also use the following code to handle "ok" button for iOS <8.0.
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 0)
{
[self performSegueWithIdentifier:#"yourSegueName" sender:self];
}
else
{
}
}