I am trying to create a UISegmentedControl programatically. I have a UIViewController in the storyboard with nothing in it.
.h file
UISegmentedControl *segmentedControl;
NSString *feedBackButtonTitle;
NSString *contactsButtonTitle;
and here are the property declarations.
#property (nonatomic,retain) IBOutlet UISegmentedControl *segmentedControl;
-(void) segmentedControlIndexChanged;
In viewDidLoad: I have initalized and added the UISegmentedControl.
NSString *language = [[NSLocale preferredLanguages] objectAtIndex:0];
if ([language isEqualToString:#"en"]){
contactsButtonTitle = [[[configFileDictionary objectForKey:#"Contacts"] objectForKey:#"Label"] objectForKey:#"en"];
feedBackButtonTitle = [[[[[configFileDictionary objectForKey:#"Contacts"] objectForKey:#"Contact"]objectForKey:#"Feedback"]objectForKey:#"Label"]objectForKey:#"en"];
}
else if([language isEqualToString:#"fr"]){
contactsButtonTitle = [[[configFileDictionary objectForKey:#"Contacts"] objectForKey:#"Label"] objectForKey:#"fr"];
feedBackButtonTitle = [[[[[configFileDictionary objectForKey:#"Contacts"] objectForKey:#"Contact"]objectForKey:#"Feedback"]objectForKey:#"Label"]objectForKey:#"fr"];
}
NSArray *itemsArray = [[NSArray alloc] initWithObjects:contactsButtonTitle, feedBackButtonTitle, nil];
segmentedControl = [[UISegmentedControl alloc] initWithItems:itemsArray];
segmentedControl.segmentedControlStyle = UISegmentedControlStylePlain;
//segmentedControl.selectedSegmentIndex = 0;
segmentedControl.frame = CGRectMake(0.0f, 0.0f, 320.0f,40.0f);
[segmentedControl addTarget:self action:#selector(segmentedControlIndexChanged) forControlEvents:UIControlEventValueChanged];
// [self.view addSubview:segmentedControl];
// Create view for contact display.
[self createViews];
and this the (void)segmentedControlIndexChanged
-(void)segmentedControlIndexChanged
{
switch (self.segmentedControl.selectedSegmentIndex)
{
case 0:
[self createViews];
break;
case 1:
[self showFeedbackForm];
break;
default:
break;
}
}
This is showing the segmented control on the screen just fine, but when I click on the options in the segmentedcontrol, it always goes into the option case 0. segmented control and opens [self createViews];
On inserting breakpoints at the line case 0, I noticed that the option _selectedSegment in segmentedControl is 1. This doesn't make any sense.
Ok so I created in my UIViewController a property segmentedControl and then wrote only that code:
- (void)viewDidLoad
{
[super viewDidLoad];
NSArray *itemsArray = [[NSArray alloc] initWithObjects:#"a", #"b", nil];
self.segmentedControl = [[UISegmentedControl alloc] initWithItems:itemsArray];
self.segmentedControl.segmentedControlStyle = UISegmentedControlStylePlain;
self.segmentedControl.selectedSegmentIndex = 0;
self.segmentedControl.frame = CGRectMake(0.0f, 0.0f, 320.0f,40.0f);
[self.segmentedControl addTarget:self action:#selector(segmentedControlIndexChanged) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:self.segmentedControl];
}
-(void)segmentedControlIndexChanged
{
switch (self.segmentedControl.selectedSegmentIndex)
{
case 0:
NSLog(#"createviews");
break;
case 1:
NSLog(#"showfeedbackform");
break;
default:
break;
}
}
It works for me perfectly - logging the proper choices.
As you say the _segmentedControl is all right - notice that I use dot notation to get segmentedControl. This might be the case since when you're not using dot notation - you're not calling the getter.
Edit
To sum up a little - segmentedControl from your .h file is redundant - it's just another UISegmentedControl. Your property can be referenced by dot notation - self.segmentedControl. Or by synthesized name (made by default) _segmentedControl.
So what you're doing is referencing to this .h object when initializing and adding your UISegmentedController but when segmentedControlIndexChanged is called - you change it in your property which is not even visible.
Ok a few things here:
Since you got a property, use self.segmentedControl instead of segmentedControl
With a simple change in your selector signature life is just easier:
[self.segmentedControl addTarget:self
action:#selector(segmentedControlIndexChanged:)
forControlEvents:UIControlEventValueChanged]; // Notice the colon
-(void)segmentedControlIndexChanged:(id)sender
{
switch ([sender selectedSegmentIndex])
{
case 0:
[self createViews];
break;
case 1:
[self showFeedbackForm];
break;
default:
break;
}
}
Related
I am new in iOS and I am facing problem regarding to get the value from custom table view cell to view controller. I am using rate view for rating and I am checking if value of rate is less then 3 then it show have to enter text in the text view and I want to get value in view controller
My code is like this
CustomTableviewcell.h
#interface NextTableview : UITableViewCell<RateViewDelegate,UITextViewDelegate>
{
NSString *StatusValue;
UILabel *lbl;
}
#property(nonatomic,strong) IBOutlet UILabel *staticlbl;
#property(nonatomic,strong) IBOutlet UITextView *commenttxtview;
#property(nonatomic,strong) IBOutlet UILabel *Kpiidlbl;
#property (weak, nonatomic) IBOutlet RateView *rateView;
#property (weak, nonatomic) IBOutlet UILabel *statusLabel;
#end
CustomTableviewcell.m
#synthesize rateView,staticlbl,statusLabel,commenttxtview,Kpiidlbl;
- (void)awakeFromNib {
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
commenttxtview.layer.borderWidth = 0.70f;
commenttxtview.layer.borderColor = [[UIColor blackColor] CGColor];
commenttxtview.delegate=self;
UIToolbar* doneToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
doneToolbar.barStyle = UIBarStyleBlackTranslucent;
doneToolbar.items = [NSArray arrayWithObjects:
[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
[[UIBarButtonItem alloc]initWithTitle:#"Done" style:UIBarButtonItemStyleDone target:self action:#selector(doneButtonClickedDismissKeyboard)],
nil];
[doneToolbar sizeToFit];
commenttxtview.inputAccessoryView = doneToolbar;
lbl = [[UILabel alloc] initWithFrame:CGRectMake(10.0, 0.0,90.0, 34.0)];
[lbl setText:#"Enter Text"];
[lbl setFont:[UIFont systemFontOfSize:12]];
[lbl setBackgroundColor:[UIColor clearColor]];
[lbl setTextColor:[UIColor lightGrayColor]];
commenttxtview.delegate = self;
[commenttxtview addSubview:lbl];
statusLabel.hidden=YES;
commenttxtview.hidden=YES;
// Do any additional setup after loading the view from its nib.
self.rateView.notSelectedImage = [UIImage imageNamed:#"not_selected_star#2x.png"];
self.rateView.halfSelectedImage = [UIImage imageNamed:#"half_selected_star#2x.png"];
self.rateView.fullSelectedImage = [UIImage imageNamed:#"selected_star#2x.png"];
self.rateView.rating = 0;
self.rateView.editable = YES;
self.rateView.maxRating = 5;
self.rateView.delegate = self;
Kpiidlbl.hidden=YES;
}
-(void)doneButtonClickedDismissKeyboard
{
[commenttxtview resignFirstResponder];
// commenttxtview.hidden=YES;
}
- (void)textViewDidEndEditing:(UITextView *)theTextView
{
if (![commenttxtview hasText]) {
lbl.hidden = NO;
}
}
- (void) textViewDidChange:(UITextView *)textView
{
if(![commenttxtview hasText]) {
lbl.hidden = NO;
}
else{
lbl.hidden = YES;
}
}
- (void)rateView:(RateView *)rateView ratingDidChange:(int)rating {
self.statusLabel.text = [NSString stringWithFormat:#"%d", rating];
NSLog(#"Rating value =%#",self.statusLabel.text);
StatusValue=statusLabel.text;
NSLog(#"Status Value String =%#",StatusValue);
// Hear I am getting value of rating..in StatusValue..
int status=[StatusValue intValue];
if(status<=3)
{
commenttxtview.hidden=NO;
}
else{
commenttxtview.hidden=YES;
}
}
How can I get label and textview value in viewcontroller and I want to set rate view value to rate view after reload table.
Hear in the Image i am getting five star and If I click on less then 3 star it should have to write comment.I am taking rate value in the label.How can I get both label and textvalue in view controller.Please tell me to update question if you want more data.Thanks in Advance!
So write this in your CustomTableViewCell.h
#property(nonatomic,assign)NSInteger selectedRating;
everytime when the rating is updated in the Cell, you have to change the value of this variable.
In the viewController it depends on when you want to get the value of this cell. For example in this method:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
CustomTableViewCell *yourCell = (CustomerTableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
NSLog(#"%lu",yourCell.selectedRating);
}
Let me know if this was helpful!
Another way without a variable is to read the NSString in the statusLabel and change the string to a NSInteger variable...
If you are using your delegate...
Then implement the delegate RateViewDelegatein the viewController. The delegate is called in the class to which it is assigned...
Try this
You have to add the #property (nonatomic, weak) NSObject<RateViewDelegate>* delegate;
to the header file of your CustomTableViewCell.h in the method
-(UITableViewCell) cellForRowAtIndexPath....
you have to assign the delegate like this
cell.delegate = self;
Now modify your cell delegate method to this
- (void)rateView:(RateView *)rateView ratingDidChange:(int)rating {
self.statusLabel.text = [NSString stringWithFormat:#"%d", rating];
NSLog(#"Rating value =%#",self.statusLabel.text);
StatusValue=statusLabel.text;
NSLog(#"Status Value String =%#",StatusValue);
// Hear I am getting value of rating..in StatusValue..
int status=[StatusValue intValue];
if(status<=3)
{
commenttxtview.hidden=NO;
}
else{
commenttxtview.hidden=YES;
}
if([self.delegate respondsToSelector:#selector(rateView:ratingDidChange:)]){
[self.delegate rateView:rateView ratingDidChange:rating];
}
}
I have declared 4 images in the ViewDidLoad in my ViewController and then hide them with myImage1.hidden = YES;.
I was wondering if there was anyway of sending a message from the App Delegate (from within a Switch Case) to the ViewController's ViewDidLoad method, which sets the UIImageView to hidden: myImage1.hidden = NO;
-(void)playIndex:(NSInteger)index
{
switch (index)
{
case 1:
[self playOne];
[// something here to tell the UIImageView .hidden = NO;]
break;
I'm not sure this is possible but thought someone might be able to shed some light on what I'm trying to do. I really just want the image to become visible at the same time as the case 1: [self playOne]; when it's called.
If not done this way, is there another other method I could try to achieve this?
`- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
AppDelegate* app = [[UIApplication sharedApplication] delegate];
UIImage *redSquare = [UIImage imageNamed:#"red_square.png"];
UIImage *blueSquare = [UIImage imageNamed:#"blue_square.png"];
UIImage *greenSquare = [UIImage imageNamed:#"green_square.png"];
UIImage *yellowSquare = [UIImage imageNamed:#"yellow_square.png"];
UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(72, 117, 60, 60)];
UIImageView *imageView2 = [[UIImageView alloc] initWithFrame:CGRectMake(188, 117, 60, 60)];
UIImageView *imageView3 = [[UIImageView alloc] initWithFrame:CGRectMake(72, 254, 60, 60)];
UIImageView *imageView4 = [[UIImageView alloc] initWithFrame:CGRectMake(188, 254, 60, 60)];
[self.view addSubview:imageView1];
[self.view addSubview:imageView2];
[self.view addSubview:imageView3];
[self.view addSubview:imageView4];
imageView1.animationImages = #[redSquare];
imageView2.animationImages = #[blueSquare];
imageView3.animationImages = #[greenSquare];
imageView4.animationImages = #[yellowSquare];
imageView1.animationDuration = 1;
imageView2.animationDuration = 1;
imageView3.animationDuration = 1;
imageView4.animationDuration = 1;
imageView1.hidden = YES;
imageView2.hidden = YES;
imageView3.hidden = YES;
imageView4.hidden = YES;
[imageView1 startAnimating];
[imageView2 startAnimating];
[imageView3 startAnimating];
[imageView4 startAnimating];
The Switch statement in the app delegate is: (Including the ViewController reference)
-(void)playIndex:(NSInteger)index
{
ViewController* mainController = (ViewController*) self.window.rootViewController;
switch (index)
{
case 1: [self playOne]; [mainController imageView1Hidden]; break;
case 2: [self playTwo]; break;
case 3: [self playThree]; break;
case 4: [self playFour]; break;
}
}
You can do this by :
Property variable of that ViewController.
By firing local Notification
It's definitely possible, although you probably shouldn't include this logic in the app delegate (but I admit I'd need more context to direct you otherwise).
You can access your view controller from the app delegate. See the answer to this question on how to do that:
How do I access my viewController from my appDelegate? iOS
Then, in your view controller you could have properties (of type BOOL) that specify whether the corresponding image views should be visible. Something like this in your view controller's .h file:
#property BOOL imageView1Hidden;
Then, in your switch statement you would set that property, and in the viewDidLoad method (of your view controller) you could check those properties to determine whether to set the hidden state for the image views.
Not entirely elegant, but it would work.
I created a custom UIButton with this code.
#implementation SessionButton
- (id)initWithFrame:(CGRect)frame withSessionObject:(SessionObject*)obj
{
self = [super initWithFrame:frame];
if (self) {
self.sessionObj = obj;
}
return self;
}
#end
And allocated with this...
SessionButton *button = [[SessionButton alloc] initWithFrame:CGRectMake(70, (startHour - 7)*80 + startMinute + 2, 220, height -4) withSessionObject:obj];
When I try to check it with an NSLog, it's perfect. I initialised the button with my object.
Now I have to give it a action. So I wrote this.
[button addTarget:self
action:#selector(viewForSessions:)
forControlEvents:UIControlEventTouchUpInside];
here is the viewForSessions method:
- (IBAction) viewForSessions:(id)sender {
SessionButton *mBut = (SessionButton*) sender;
SessionObject *obj = mBut.sessionObj;
NSString *title = nil;
switch (obj.type) {
case 2:
title = #"Konferans";
break;
case 3:
title = #"Panel";
break;
case 4:
title = #"İnteraktif";
break;
case 5:
title = #"Forum";
break;
} //and it goes on....... a bit long
My problem is, after calling the selector, the id named sender A button, I checked with an NSLog. But it is not my button. It doesn't have any initialised SessionObject, it returns nil. Am I doing something wrong? Some help would be great.
Try with following code:
- (IBAction) viewForSessions:(SessionButton *)sender
{
SessionObject *obj = sender.sessionObj;
NSString *title = nil;
switch (obj.type) {
.
.
}
I have a view controller that is calling a custom UIView via an IBAction.The custom view contains a UIPickerView that slides up from the bottom of the screen and a toolbar with 'cancel' and 'done' buttons above it. The problem is that the view only appears on the screen after being called for the second time. Using breakpoints I can verify that every single line of code is being called both times. Everything seems to be happening the same way each time. Nothing is NIL, and in fact it's like this for the duration that the app is running, not only the first time it's called. You always have to click the button twice to get the view to appear for as long as the app is running.
Admittedly, the code for the custom picker view is not mine. I copied it from someone else's example. I'm not sure if it's the problem or not. I don't see how it could be, but I'm a bit over my head here. This is how I'm calling the view from my view controller.
- (IBAction)statusPickerButtonPressed:(id)sender {
self.scrollPickerView = [[StatusPickerView alloc]init];
[self.navigationController.view addSubview:self.scrollPickerView];
self.scrollPickerView.delegate = self;
self.scrollPickerView.dataSource = self;
}
and here's the custom UIView
#import "StatusPickerView.h"
#interface StatusPickerView ()
#property NSArray *pickerArray;
#property NSInteger selectedRow;
#end
#implementation StatusPickerView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setToolbar];
[self becomeFirstResponder];
float screenWidth = [UIScreen mainScreen].bounds.size.width;
float pickerWidth = screenWidth * 3 / 4;
float xPoint = screenWidth / 2 - pickerWidth / 2;
[self setFrame: CGRectMake(xPoint, 50.0f, pickerWidth, 180.0f)];
self.showsSelectionIndicator = YES;
[self selectRow:3 inComponent:0 animated:YES];
}
return self;
}
-(void)setToolbar
{
_toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
[_toolbar setBarStyle:UIBarStyleDefault];
UIBarButtonItem * btnCancel = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel
target:self action:#selector(barbtnPressed:)];
UIBarButtonItem * flexible = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:nil action:nil];
UIBarButtonItem * btnDone = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self action:#selector(barbtnPressed:)];
[btnCancel setTag:1];
[btnCancel setStyle:UIBarButtonItemStyleBordered];
[btnDone setTag:2];
[btnDone setStyle:UIBarButtonItemStyleBordered];
NSArray * btnArray = [[NSArray alloc] initWithObjects:btnCancel, flexible, btnDone, nil];
[_toolbar setItems:btnArray];
self.inputAccessoryView = _toolbar;
self.inputView = self;
}
-(BOOL)canBecomeFirstResponder
{
return true;
}
-(void)barbtnPressed:(id)sender
{
NSInteger tag = [sender tag];
switch (tag) {
case 1:
{
[self removeFromSuperview];
break;
}
case 2:{
[self removeFromSuperview];
self.selectedRow = [self selectedRowInComponent:0];
[[NSNotificationCenter defaultCenter]postNotificationName:#"user_selected_new_section" object:self];
}
default:
break;
}
}
-(int)giveSelectedRow{
return self.selectedRow;
}
I'm fully prepared to feel foolish here, as the solution is probably obvious, just not obvious to myself.
edit:
I tried using [self.view.window addSubview:self.scrollPickerView]; instead of [self.navigationController.view addSubview:self.scrollPickerView];, and the behavior is exactly the same.
This line:
[self.navigationController.view addSubview:self.scrollPickerView];
should read:
[self.view addSubview:self.scrollPickerView];
You’re calling -init instead of -initWithFrame:, so your view is ending up with the default frame of CGRectZero. Considering that you’re then making a frame of your own, that call might as well pass that in to start out with:
self.scrollPickerView = [[ScrollPickerView alloc] initWithFrame:CGRectZero];
Alternatively, you could keep the current self.scrollPickerView = … code and change the -initWithFrame: to an -init, like this:
- (id)init
{
float screenWidth = [UIScreen mainScreen].bounds.size.width;
float pickerWidth = screenWidth * 3 / 4;
float xPoint = screenWidth / 2 - pickerWidth / 2;
self = [super initWithFrame:CGRectMake(xPoint, 50.0f, pickerWidth, 180.0f)];
if (self) {
[self setToolbar];
[self becomeFirstResponder];
self.showsSelectionIndicator = YES;
[self selectRow:3 inComponent:0 animated:YES];
}
return self;
}
I have created a NSArray that contains images objects. Based on the swipe direction recognized by UISwipeGestureRecognizerDirection the index is incremented up or down so the right image could be selected.
The problem I have is that my NSArray is returning a NULL value instead of the image object. Therefore the UIImageView (named imageView) displays nothing.
I am printing an NSLog statement in order to see what is really happening - example below:
... [2307:60b] Swiped and the index is: 1, the image is (null) and the total number of objects 2
As per NSLog statement above we can see that:
- The number of objects is perfectly counted.
- NSArray index increments perfectly up and down.
- But a NULL value is returned for the image object.
My code below (see the handleSwipe method):
#synthesize imageView;
int imageIndex = 1;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor whiteColor];
imageView.center = CGPointMake(CGRectGetWidth(self.view.bounds)/2.0f, CGRectGetHeight(self.view.bounds)/2.0f+20);
[self.view addSubview:imageView];
UISwipeGestureRecognizer *swipeRightGesture=[[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(handleSwipe:)];
[self.view addGestureRecognizer:swipeRightGesture];
swipeRightGesture.direction = UISwipeGestureRecognizerDirectionRight;
UISwipeGestureRecognizer *swipeLeftGesture=[[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(handleSwipe:)];
[self.view addGestureRecognizer:swipeLeftGesture];
swipeRightGesture.direction = UISwipeGestureRecognizerDirectionLeft;
UIBarButtonItem *dismiss_btn = [[UIBarButtonItem alloc] initWithTitle:#"Done" style:UIBarButtonItemStylePlain target:self action:#selector(dismissModal:)];
self.navigationItem.rightBarButtonItems = [NSMutableArray arrayWithObjects:dismiss_btn, nil];
}
- (IBAction)handleSwipe:(UIGestureRecognizer *)sender {
int theTotal;
NSArray *images=[[NSArray alloc] initWithObjects: #"image021.jpg", #"image041.jpg", nil];
UISwipeGestureRecognizerDirection direction = [(UISwipeGestureRecognizer *) sender direction];
switch (direction) {
case UISwipeGestureRecognizerDirectionLeft:
imageIndex++;
break;
case UISwipeGestureRecognizerDirectionRight:
imageIndex--;
break;
default:
break;
}
imageIndex = (imageIndex < 0) ? ([images count] -1): imageIndex % [images count];
imageView.image = [UIImage imageNamed:[images objectAtIndex:imageIndex]];
theTotal = [images count];
NSLog(#"Swiped and the index is: %d, the image is %# and the total number of objects %d", imageIndex, imageView.image, theTotal);
}
In your .h file (if the UIImageView is not in interface builder), change the property declaration to:
#property (nonatomic, strong) UIImageView *imageView;
You could take out the strong and leave it as (nonatomic), but if you're unfamiliar with weak vs. strong, it's good for reference. If you were to leave it as weak, the object would get released immediately after assignment within this view controller since there would be no other strong pointers to it.
If the UIImageView was not set up in interface builder, then you need to create it in the implementation:
- (void)viewDidLoad
{
_imageView = [[UIImageView alloc] init];
...
}
If this isn't the case, then make sure your capitalization, spelling, etc. is correct when referencing the images and that all images are added to the application target in your project settings.