I have 2 ViewControllers. After login it will move to the next screen. Then one logout button will be appear. After user press log out button it should return to login screen with an empty text field.
How would I do that? I tried all ways, but it doesn't seem to work.
My first ViewController:
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.sampleDictionary = #{#"username":#"alex", #"password":#"1234"};
}
- (IBAction)loginTapped
{
if ([self.sampleDictionary[#"password"] isEqualToString:passwordField.text]) {
[self performSegueWithIdentifier:#"ss" sender:self];
} else {
// Alert message
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"wrong" message:#"Message" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:#"Ok" style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:actionOk];
[self presentViewController:alertController animated:YES completion:nil];
}
}
#end
This is my second ViewController:
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.hidesBackButton = YES;
}
- (IBAction)logout:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
In your ViewController remove the text for username and password fields in viewWillAppear.
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
usernameField.text = #"";
passwordField.text = #"";
}
In your second ViewController:
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *logoutButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 100, 320, 50)];
[logoutButton setTitle:#"Log Out" forState:UIControlStateNormal];
[logoutButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[logoutButton setBackgroundColor:[UIColor blackColor]];
[logoutButton addTarget:self action:#selector(logout) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:logoutButton];
}
- (void)logout
{
[self dismissViewControllerAnimated:YES completion:nil];
}
Related
I have stored 5 images in an NSMutableArray named as _dict in the code.
In .h file:
#property(weak,nonatomic)IBOutlet UIButton *b1;
#property(weak,nonatomic)IBOutlet UIButton *b2;
#property(weak,nonatomic)IBOutlet UIButton *b3;
#property(weak,nonatomic)IBOutlet UIButton *b4;
#property(weak,nonatomic)IBOutlet UIButton *b5;
#property(weak,nonatomic)IBOutlet UIButton *b6;
#property(weak,nonatomic)IBOutlet UIButton *b7;
#property(weak,nonatomic)IBOutlet UIButton *b8;
#property(weak,nonatomic)IBOutlet UIButton *b9;
In.m file
dict=[[NSMutableArray alloc]init];
dict= _array;
NSLog(#"%#",dict);
colorimage = [dict objectAtIndex:0];
[_b1 setBackgroundImage:colorimage forState:UIControlStateNormal];
colorimage1 = [dict objectAtIndex:1];
[_b2 setBackgroundImage:colorimage1 forState:UIControlStateNormal];
colorimage2 = [dict objectAtIndex:2];
[_b3 setBackgroundImage:colorimage2 forState:UIControlStateNormal];
colorimage3 = [dict objectAtIndex:3];
[_b4 setBackgroundImage:colorimage3 forState:UIControlStateNormal];
colorimage4 = [dict objectAtIndex:4];
[_b5 setBackgroundImage:colorimage4 forState:UIControlStateNormal];
int j=0;
img=[[NSMutableArray alloc]init];
}
-(IBAction)button1:(id)sender{
k++;
[img addObject:colorimage];
[sender setBackgroundImage:[UIImage imageNamed:#"apple.png"] forState:UIControlStateNormal];
[self check];
}
-(IBAction)button2:(id)sender{
k++;
[img addObject:colorimage1];
[sender setBackgroundImage:[UIImage imageNamed:#"apple.png"] forState:UIControlStateNormal];
[self check];
}
-(IBAction)button3:(id)sender
{
k++;
[img addObject:colorimage2];
[sender setBackgroundImage:[UIImage imageNamed:#"apple.png"] forState:UIControlStateNormal];
[self check];}
-(IBAction)button4:(id)sender
{
k++;
[img addObject:colorimage3];
[sender setBackgroundImage:[UIImage imageNamed:#"apple.png"] forState:UIControlStateNormal];
[self check];
}
-(IBAction)button5:(id)sender
{
k++;
[img addObject:colorimage4];
[sender setBackgroundImage:[UIImage imageNamed:#"apple.png"] forState:UIControlStateNormal];
[self check];
}
-(IBAction)button6:(id)sender
{
}
-(IBAction)button7:(id)sender
{
}
-(IBAction)button8:(id)sender
{
}
-(IBAction)button9:(id)sender
{
}
-(void)check{
if(k==5)
{
// NSArray *arr1 = [[NSArray alloc]initWithObjects:#"aa",#"bb",#"1",#"cc", nil];
// NSArray *arr2 = [[NSArray alloc]initWithObjects:#"aa",#"bb",#"1",#"cc", nil];
if([dict isEqualToArray:img])
{
NSLog(#"equal");
UIAlertController * alert=[UIAlertController alertControllerWithTitle:#"Title"
message:#"Message"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* Retry = [UIAlertAction actionWithTitle:#"you got"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
NSLog(#"you pressed Yes, please button");
// call method whatever u need
}];
[alert addAction:Retry];
[self presentViewController:alert animated:YES completion:nil];
}
else{
NSLog(#"not equal........");
UIAlertController * alert=[UIAlertController alertControllerWithTitle:#"Title"
message:#"Message"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* Retry = [UIAlertAction actionWithTitle:#"please try again............"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
NSLog(#"you pressed Yes, please button");
// call method whatever u need
}];
[alert addAction:Retry];
[self presentViewController:alert animated:YES completion:nil];
}
}
// else
// {
// UIAlertController * alert=[UIAlertController alertControllerWithTitle:#"Title"
// message:#"Message"
// preferredStyle:UIAlertControllerStyleAlert];
// UIAlertAction* Retry = [UIAlertAction actionWithTitle:#"please try again"
// style:UIAlertActionStyleDefault
// handler:^(UIAlertAction * action)
// {
// NSLog(#"you pressed Yes, please button");
// call method whatever u need
// }];
// [alert addAction:Retry];
// [self presentViewController:alert animated:YES completion:nil];
// }
}
i got the images.But as i told ,i have stored 5 images in dict.i need to display the images randomly tag of UIbutton.I tried with many code.But not got.
And also i have stored 10 images in NSMutableArray .And i need to select randomly 4 images from the array and need to display the image where unfilled uibutton img(that is...already 5 images will display on different tag of UIButtons and remaining 4 UIButton should display the images which is stored in array of 10 images).how to do?
The good way to use is to go for IBOutletCollection.
Instead of creating so many outlets you can use IBOutletCollection and make your code small. When you do that you can collect all your 9 buttons inside one array.
#IBOutlet var buttons: [UIButton]!
Now let's assume you have random tags generated - use some random generator - and stored inside:
var randomTags: [Int]
Now you can use this beautiful Swift syntax to filter and get new buttons array which has only those buttons whose tag is randomly generated and stored inside randomTags
let newButtons = buttons.filter { (button) -> Bool in
return randomTags.contains(button.tag)
}
Hope it helps.
Here is my View,
In this view, except Description field all are UITextfield and Description field is UITextView.
So what I want is that when I navigate to this view,
If I made some changes or modification then only save button will be enabled
And If I edited some fields' values and tried to go back to previous screen without saving it, following alert should pop up.
How to achieve it ? Thanks.
check following example, I hope it will help you.
#import "SampleViewController.h"
#interface SampleViewController ()
#end
#implementation SampleViewController
- (void)viewDidLoad {
[super viewDidLoad];
_textview.delegate = self;
_secondButton.hidden = YES;
self.textview.layer.borderWidth = 2.0f;
self.textview.layer.borderColor = [[UIColor grayColor] CGColor];
self.navigationItem.hidesBackButton = YES;
UIBarButtonItem *newBackButton = [[UIBarButtonItem alloc] initWithTitle:#"< back" style:UIBarButtonItemStylePlain target:self action:#selector(back:)];
self.navigationItem.leftBarButtonItem = newBackButton;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)textViewDidBeginEditing:(UITextView *)textView{
_secondButton.hidden = NO;
}
- (void) back:(UIBarButtonItem *)sender {
UIAlertController* alert = [UIAlertController alertControllerWithTitle:#"Attention"
message:#"Are you sure want to discard this message."
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
self.textview.text = nil;
[self.navigationController popViewControllerAnimated:YES];
}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
NSLog(#"sandip");
[self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)secondButton:(id)sender {
}
#end
Use a validator functions to validate the whole form by checking if any of the fields text count is > 0. To make your life easier, there are a few validators out there, which you can use such as, RAFieldValidator. Look out for more on github. Check these out https://github.com/search?utf8=%E2%9C%93&q=form+validator+ios&type=
Coming to triggering this function,
For Text field: check this out, UITextField text change event
For TextView: You need to set UITextView delegate and implement textViewDidChange: Method in it.
Recently, a strange question occurred when I pushViewController to the next viewController.
Why I think it's a strange question? because it don't always appears(The probability of occurrence is low). when it appears, next viewController only shows its nav bar on screen, I still can see the rootViewController, but touching it without reaction(PopGesture is effective).Hoping for your help, thanks very much.
#pragram mark - method of pushing
- (void)clickToAccout {
if (![self countTotalSelectedNumber]) {
[SVProgressHUD showInfoWithStatus:#"没有被选择的商品"];
return;
}
CSCreatOrderViewController *creatOrderVC = [[CSCreatOrderViewController alloc] init];
creatOrderVC.totalPrice = [self countTotalPrice];
creatOrderVC.goods = [self selectedGoods];
[self.navigationController pushViewController:creatOrderVC animated:YES];
}
#pragma mark - chlid class of navgationController
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationBar.tintColor = [UIColor whiteColor];
}
- (UIStatusBarStyle)preferredStatusBarStyle {
return _barStyle;
}
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated{
if (self.viewControllers.count > 0) {
viewController.hidesBottomBarWhenPushed = YES;
[SVProgressHUD dismiss];
}
[super pushViewController:viewController animated:animated];
}
- (UIViewController *)popViewControllerAnimated:(BOOL)animated {
[SVProgressHUD dismiss];
return [super popViewControllerAnimated:animated];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - tabBarController
- (void)viewDidLoad {
[super viewDidLoad];
CSTabBar *tabBar = [[CSTabBar alloc] init];
[self setValue:tabBar forKey:#"tabBar"];
[self.tabBar setTintColor:[UIColor cz_colorWithHex:0Xec5151]];
[self addChildViewControllerWithTitle:#"首页" imageName:#"home" controllerName:#"CSHomeViewController"];
[self addChildViewControllerWithTitle:#"分类" imageName:#"classify" controllerName:#"CSClassifyViewController"];
[self addChildViewControllerWithTitle:#"查询" imageName:#"search" controllerName:#"CSSearchViewController"];
[self addChildViewControllerWithTitle:#"购物车" imageName:#"cart" controllerName:#"CSShoppingCartViewController"];
[self addChildViewControllerWithTitle:#"我的" imageName:#"mine" controllerName:#"CSMineViewController"];
self.selectedIndex = 0;
}
- (void)addChildViewControllerWithTitle:(NSString *)title imageName:(NSString *)imageName controllerName:(NSString *)controllerName {
Class cls = NSClassFromString(controllerName);
UIViewController *vc = [[cls alloc] init];
vc.title = title;
[vc.tabBarItem setImage:[UIImage imageNamed:[NSString stringWithFormat:#"%#",imageName]]];
[vc.tabBarItem setSelectedImage:[UIImage imageNamed:[NSString stringWithFormat:#"%#_selected",imageName]]];
vc.tabBarItem.title = title;
CSNavigationController *nav = [[CSNavigationController alloc] initWithRootViewController:vc];
[self addChildViewController:nav];
}
#pragma mark - base viewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
[self setupNavItem];
self.navigationController.interactivePopGestureRecognizer.enabled = YES;
self.navigationController.interactivePopGestureRecognizer.delegate = self;
_indciatorView = [[CSIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
UIWindow *keyW = [UIApplication sharedApplication].keyWindow;
[keyW addSubview:_indciatorView];
[_indciatorView mas_makeConstraints:^(MASConstraintMaker *make) {
make.center.equalTo(keyW);
}];
}
- (void)setupNavItem {
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
button.imageEdgeInsets = UIEdgeInsetsMake(9, 0, 9, 29);
[button setImage:[UIImage imageNamed:#"left"] forState:UIControlStateNormal];
[button addTarget:self action:#selector(clickToDismiss) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
}
- (void)clickToDismiss {
[self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
I think you should change
[super pushViewController:viewController animated:animated];
to
[self.navigationController pushViewController:viewController animated:animated];
And the same when pop
[super popViewControllerAnimated:animated];
to
[self.navigationController popViewControllerAnimated:animated];
I clear the cache of Xcode, this case don't appear. Maybe I Imported a third lib ago caused this case. But like what I asked ,it don't always appears(The probability of occurrence is low). So, hoping it has been well.
i have a custom cell for a table, is working fine,
Im showing a list of products in the cells, when the user touches a button "delete", i show an alert view to confirm deletion,
but I need to show the name of the product in the alert view: "are you sure you want to delete XXX?"
here the code for my custom cell
Please note the call to the alert view in deleteCartButtonPressed
#import "ShoppingCartProductsCell.h"
#import "Product.h"
#implementation ShoppingCartProductsCell
#synthesize categoryNameLabel = _categoryNameLabel;
#synthesize productNameLabel = _productNameLabel;
#synthesize quantityPicker = _quantityPicker;
#synthesize deleteCartButton = _deleteCartButton;
#synthesize product = _product;
- (void) dealloc {
[_deleteCartButton release];
[_categoryNameLabel release];
[_productNameLabel release];
[_quantityPicker release];
[super dealloc];
}
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
//self = [super initWithFrame:frame];
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
[self initQuantityPicker];
[self initLabels]; //y picker!
[self initButtons];
}
return self;
}
- (void) initQuantityPicker {
CGRect contentRect = self.contentView.bounds;
CGFloat boundsX = contentRect.origin.x;
self.quantityPicker = [[[BDFDropDownList alloc] initWithFrame:CGRectMake(boundsX+220, 8, 61, 28) popupWidth:90]autorelease];
self.quantityPicker.delegate = self;
for (int i = 1; i<=20; i++) {
[self.quantityPicker addOptionWithName:[NSString stringWithFormat:#"%d",i] value:[NSNumber numberWithInt:i]];
}
[self.contentView addSubview:self.quantityPicker];
}
- (void) initLabels {
self.productNameLabel = [[[UILabel alloc]init] autorelease];
self.productNameLabel.textAlignment = UITextAlignmentLeft;
self.productNameLabel.backgroundColor = [UIColor clearColor];
self.productNameLabel.font = [UIFont fontWithName:#"HelveticaNeue" size:15];
self.productNameLabel.textColor = [UIColor colorWithRed:102/255.0f green:102/255.0f blue:102/255.0f alpha:1];
[self.contentView addSubview:self.productNameLabel];
}
- (void) initButtons {
self.deleteCartButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.deleteCartButton addTarget:self action:#selector(deleteCartButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.deleteCartButton setImage:[UIImage imageNamed:#"deleteCartButton.png"] forState:UIControlStateNormal];
[self.contentView addSubview:self.deleteCartButton]; //Calculations For stage 2
}
- (void)layoutSubviews {
[super layoutSubviews];
CGRect contentRect = self.contentView.bounds;
CGFloat boundsX = contentRect.origin.x;
CGRect frame;
frame= CGRectMake(boundsX+10 ,10, 200, 20);
self.productNameLabel.frame = frame;
frame= CGRectMake(boundsX+330 ,8, 30, 29); //310
self.deleteCartButton.frame = frame;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void) setProduct:(Product*)product {
[self setProduct:product withQuantity:0];
}
- (void) setProduct:(Product*)product withQuantity:(NSInteger)quantity {
[_product release];
_product = product;
[_product retain];
self.productNameLabel.text = product.SKU;
self.quantityPicker.delegate = nil;
[self.quantityPicker setSelectedIndex:quantity-1]; //testa
self.quantityPicker.delegate = self;
}
- (void) deleteCartButtonPressed:(id) sender {
NSLog(#"Delete ");
UIAlertView *deleteAlert = [[UIAlertView alloc]initWithTitle:#"Attention" message:#"Are you sure you want to delete this record?" delegate:nil cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok", nil];
[deleteAlert show];
[deleteAlert release];
}
#end
Thanks a lot!
string literals are your friend.
- (void) deleteCartButtonPressed:(id) sender {
NSLog(#"Delete ");
UIAlertView *deleteAlert = [[UIAlertView alloc]initWithTitle:#"Attention" message:[NSString stringWithFormat:#"Are you sure you want to delete %#?", [myTableDatasource objectAtIndex:idx]], delegate:nil cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok", nil];
[deleteAlert show];
[deleteAlert release];
}
It's probably best to move this out of your cell subclass and into your datasource and delegate so as to facilitate cleaner code.
I just spent most of a day tracking down a very strange case where calling resignFirstResponder on the active UITextField did not hide the keyboard, even though the textfield was the first responder. This happens when I push a view controller on top of another view controller with an active text field. The keyboard goes away (as expected). But if I bring the keyboard back by touching a textfield in the 2nd view controller, subsequent calls to resignFirstResponder have no effect.
Here's simple code to reproduce the issue. This code is a view controller with a nav bar button to hide the keyboard, and another to push another copy of itself (with a confirmation UIAlertView). The first copy works without problem. However, if you push a 2nd copy (when the first copy has a visible keyboard) it is impossible to dismiss the keyboard. This only happens if there is a UIAlertView (the confirmation) on the screen when the 2nd copy is pushed. If you remove the #define ALERT line, everything works.
Does anyone know what is happening here? It looks like the UIALertView window is somehow interfering with the keyboard and keeping it's window from disappearing, which then confuses the next view. Is there any solution here other than pushing the 2nd view controller on a timer after the UIALertView is gone?
Sorry for the complex description. This is runnable code. I hope that the code is clear.
#implementation DemoViewController
- (id) init {
if (!(self = [super init]))
return nil;
return self;
}
- (void) dealloc {
[_inputTextfield release];
[super dealloc];
}
- (void) loadView {
UIView *view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
_inputTextfield = [[UITextField alloc] initWithFrame:CGRectMake(0., 0., 320., 44.)];
_inputTextfield.borderStyle = UITextBorderStyleRoundedRect;
_inputTextfield.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
_inputTextfield.keyboardAppearance = UIKeyboardAppearanceAlert;
_inputTextfield.autocapitalizationType = UITextAutocapitalizationTypeNone;
_inputTextfield.autocorrectionType = UITextAutocorrectionTypeNo;
_inputTextfield.keyboardType = UIKeyboardTypeDefault;
[view addSubview:_inputTextfield];
self.view = view;
[view release];
}
- (void) viewWillAppear:(BOOL) animated {
[super viewWillAppear:animated];
UIButton *downButton = [UIButton buttonWithType:UIButtonTypeCustom];
[downButton setTitle: #"keyboard down" forState:UIControlStateNormal];
[downButton addTarget:self action:#selector(downButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[downButton sizeToFit];
self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:downButton] autorelease];
UIButton *nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
[nextButton setTitle: #"next" forState:UIControlStateNormal];
[nextButton addTarget:self action:#selector(nextButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[nextButton sizeToFit];
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:nextButton] autorelease];;
}
- (void) viewWillDisappear:(BOOL) animated {
[super viewWillDisappear:animated];
[_inputTextfield resignFirstResponder];
}
- (void) downButtonPressed:(id)sender {
[_inputTextfield resignFirstResponder];
}
#define ALERT
- (void) alertView:(UIAlertView *) alertView didDismissWithButtonIndex:(NSInteger) buttonIndex {
if (alertView.cancelButtonIndex == buttonIndex) {
return;
}
[self _nextButtonPressed];
}
- (void) _nextButtonPressed {
DemoViewController *nextViewController = [[DemoViewController alloc] init];
[self.navigationController pushViewController:nextViewController];
[nextViewController release];
}
- (void) nextButtonPressed:(id)sender {
#ifdef ALERT
UIAlertView *alert = [[UIAlertView alloc] init];
alert.message = #"Next view?";
alert.cancelButtonIndex = [alert addButtonWithTitle:#"No"];
[alert addButtonWithTitle:#"Yes"];
alert.delegate = self;
[alert show];
[alert release];
#else
[self _nextButtonPressed];
#endif
}
If you had bad luck resigning your first responders, here are a few solutions that might help:
Determine who has remained the first responder after your last call to resign first responder.
Try resigning all first responders by a single call to self.view (container view)
[self.view endEditing:YES];
ONLY if you've tried all the above methods and none worked, consider using this workaround.
-(BOOL)textViewShouldEndEditing:(UITextView *)textView {
NSArray *wins = [[UIApplication sharedApplication] windows];
if ([wins count] > 1) {
UIWindow *keyboardWindow = [wins objectAtIndex:1];
keyboardWindow.hidden = YES;
}
return YES;
}