Custom UIButton, -(IBAction)action:(id)sender fail - ios

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) {
.
.
}

Related

Why accessibilityElementDidBecomeFocused is not firing for UIBarButtonItem

I'd like to know when BarButton items gets the accessibility focus or loses the accessibility focus and so I implemented the informal protocol methods of UIAccessibilityFocus but it's not still firing.
extension UIBarButtonItem {
override open func accessibilityElementDidBecomeFocused() {
if self.accessibilityElementIsFocused() {
print("My element has become focused.")
}
}
override open func accessibilityElementDidLoseFocus() {
if self.accessibilityElementIsFocused() {
print("My element has lost focus.")
}
}
override open func accessibilityElementIsFocused() -> Bool {
if (self.accessibilityIdentifier == "hamburger") {
return true
} else {
return false
}
}
I imported the swift file into viewcontroller as well
#import "Sample-Swift.h"
then I tried subclassing and implemented the methods that also didn't work
.h header file
#import <UIKit/UIKit.h>
#import <UIKit/UIAccessibility.h>
NS_ASSUME_NONNULL_BEGIN
#interface HamburgerButton : UIBarButtonItem
#end
NS_ASSUME_NONNULL_END
.m implementation file
#implementation HamburgerButton
- (BOOL)isAccessibilityElement
{
return YES;
}
- (void)accessibilityElementDidBecomeFocused {
if ([self accessibilityElementIsFocused]) {
NSLog(#"My element has become focused.");
}
}
- (void)accessibilityElementDidLoseFocus {
if ([self accessibilityElementIsFocused]) {
NSLog(#"My element has lost focus.");
}
}
- (BOOL)accessibilityElementIsFocused {
if ([self.accessibilityIdentifier isEqualToString:#"hamburger"]) {
return YES;
} else {
return NO;
}
}
#end
Here is the implementation in view controller
HamburgerButton *leftButton = [[HamburgerButton alloc]
initWithTitle:#"Hamburger"
style:UIBarButtonItemStylePlain
target:self
action:#selector(flipView:)];
leftButton.accessibilityIdentifier=#"Hamburger";
leftButton.tag = 88;
leftButton.isAccessibilityElement = YES;
HamburgerButton *rightButton = [[HamburgerButton alloc]
initWithTitle:#"Chat"
style:UIBarButtonItemStylePlain
target:self
action:#selector(flipView:)];
rightButton.accessibilityIdentifier=#"Chat";
rightButton.tag = 89;
rightButton.isAccessibilityElement = YES;
self.navigationItem.leftBarButtonItem = leftButton;
self.navigationItem.rightBarButtonItem = rightButton;
Even though the focus comes and goes away from bar button , I'm not getting the call back on accessibilityElementDidBecomeFocused
Any ideas what could be done to get accessibilityElementDidBecomeFocused firing ?
Update 1:
I could achieve this functionality by the means of notification observer but it's not giving enough information about the receiver of focus so couldn't differentiate one bar button from the other.
[[NSNotificationCenter defaultCenter]addObserver:self selector:#selector(hamburgerGotFocus:) name:UIAccessibilityElementFocusedNotification object:nil];
and find the selector method below
-(void)hamburgerGotFocus:(NSNotification *) notification{
NSLog(#"Focus:%#",notification);
UIView *receiver = notification.userInfo[#"UIAccessibilityFocusedElementKey"];
if(receiver!=nil){
NSString *strElement = [[NSString alloc]initWithFormat:#"%#",notification.userInfo[#"UIAccessibilityFocusedElementKey"]];
if([strElement containsString:#"UIButtonBarButton"]){
}
}
}
Here is the log of notification
2022-10-12 18:57:03.992859+0530 Sample[32427:1579550] Focus:NSConcreteNotification 0x280ac9980 {name = UIAccessibilityElementFocusedNotification; userInfo = {
UIAccessibilityAssistiveTechnologyKey = UIAccessibilityNotificationVoiceOverIdentifier;
UIAccessibilityFocusedElementKey = "<_UIButtonBarButton: 0x10690fce0; frame = (0 0; 49 44); tintColor = UIExtendedSRGBColorSpace 0 1 0 1; gestureRecognizers = <NSArray: 0x2804262e0>; layer = <CALayer: 0x280afa9e0>>";
}}
Update 2:
I tried doing this with UIlabel using Category and subclassing both worked
#interface SampleLabel : UILabel
#end
#implementation SampleLabel
- (void)accessibilityElementDidBecomeFocused {
NSLog(#"accessibilityIdentifier:%#",self.accessibilityIdentifier);
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, #"sample label from subclass");
}
- (void)accessibilityElementDidLoseFocus {
if ([self accessibilityElementIsFocused]) {
NSLog(#"My element has lost focus.subclass");
}
}
- (BOOL)accessibilityElementIsFocused {
return YES;
}
#end
By means of category
#interface UILabel (SampleLabel1)
#end
#implementation UILabel (SampleLabel1)
- (void)accessibilityElementDidBecomeFocused {
NSLog(#"accessibilityIdentifier:%#",self.accessibilityIdentifier);
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, #"sample label from category");
}
- (void)accessibilityElementDidLoseFocus {
if ([self accessibilityElementIsFocused]) {
NSLog(#"My element has lost focus.Category");
}
}
- (BOOL)accessibilityElementIsFocused {
return YES;
}
#end
I'm wondering whether accessibilityElementDidBecomeFocused is not compatible with UIBarButtonItem ?
FYI:
I'm following this tutorial to implement accessibilityElementDidLoseFocus.
accessibilityElementDidBecomeFocused
is not firing for bar button but it's firing for UIButton. So I just created a bar button using UIButton like below and the problem is fixed
// Image
UIImage *img1 = [UIImage imageNamed:#"img1"];
// Button
UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
[btn1 setImage:img1 forState:UIControlStateNormal];
btn1.frame = CGRectMake(0.0, 0.0, img1.size.width, img1.size.height);
btn1.tintColor = [UIColor greenColor];
[btn1 addTarget:self action:#selector(barButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
// Bar button
UIBarButtonItem *barButton1 = [[UIBarButtonItem alloc]initWithCustomView:btn1];
// Accessibility element
btn1.isAccessibilityElement = true;
img1.isAccessibilityElement = false;
btn1.accessibilityLabel = #"some accessibility text";
btn1.accessibilityTraits = UIAccessibilityTraitNone;
self.navigationItem.rightBarButtonItem = barButton1;

UIButton not working inside UITableView(crashes on tap)? Can I get some help for obj-c

SOLUTION: it was stupidly simple, I overlooked the need to declare the method for my button function in this implementation, the fix was simply adding this in the right spot (inside the implementation... duh!)
-(void)bugButton { //do stuff }
Found some code for a button that looked like what I wanted. After adding & compiling the button crashes my app when tapped, any idea why? Heres the entire cell, pretty new to making these so its hacked together from other stuff, the button stuff is near the top. I do have the method in a different place (and have used boring PSButtonCell's successfully so I know that the method works)
#interface harpButtonCell : PSTableCell <PreferencesTableCustomView> {
}
#end
#implementation harpButtonCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(id)reuseIdentifier specifier:(id)specifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier specifier:specifier];
if (self) {
// icon
UIImage *bugImage = [[UIImage alloc] initWithContentsOfFile:[NSString stringWithFormat:#"%#/Bug.png", kSelfBundlePath]];
UIButton *bugbutton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 75, 75)];
[bugbutton setImage:bugImage forState:UIControlStateNormal];
[bugbutton addTarget:self action:#selector(bugButton) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:bugbutton];
/*
UIImage *paypalImage = [[UIImage alloc] initWithContentsOfFile:[NSString stringWithFormat:#"%#/Paypal.png", kSelfBundlePath]];
UIButton *paypalbutton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 75, 75)];
[paypalbutton setImage:paypalImage forState:UIControlStateNormal];
[paypalbutton addTarget:self action:#selector(paypalButton) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:paypalbutton];*/
//int width = self.contentView.bounds.size.width;
}
return self;
}
- (instancetype)initWithSpecifier:(PSSpecifier *)specifier {
return [self initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"harpButtonCell" specifier:specifier];
}
- (void)setFrame:(CGRect)frame {
frame.origin.x = 0;
[super setFrame:frame];
}
- (CGFloat)preferredHeightForWidth:(CGFloat)arg1{
return 100.0f;
}
- (CGFloat)preferredHeightForWidth:(CGFloat)width inTableView:(id)tableView {
return [self preferredHeightForWidth:width];
}
#end
It seems that you don't implement the action of button, try to add the action in the cell:
-(void)bugButton{
NSLog(#"you clicked on button");
}

Correct use of Enum, Button always the same text

I didn't know where to search for my question, but I am very confused about this.
The premise is: I have one ViewController X that calls ViewController Y and depending on which button is selected in X, I want a different button title for ViewController Y.
In ViewController X, (SSPhotosSelectionView is ViewController Y in this case):
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
SSPhotoSelectionViewController *controller = [[SSPhotoSelectionViewController alloc] init];
if ([segue.identifier isEqualToString:#"SelectPhotosSegue"]) {
if (self.albumsButton.selected) {
[controller.downloadButton setText:SSPhotosButtonTextAdd];
}
else if (self.galleryButton.selected) {
[controller.downloadButton setText:SSPhotosButtonTextDownload];
}
}
}
As you can see from the code, if albumsButton is selected, I want the downloadButton in SSPhotoSelectionViewController to say "Add", otherwise, say "Download".
downloadButton in this case, is a SSPhotosButton object, which is a subclass of UIButton:
SSPhotosButton.h:
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSInteger, SSPhotosButtonText) {
SSPhotosButtonTextDownload = 0,
SSPhotosButtonTextAdd = 1,
};
#interface SSPhotosButton : UIButton
#property (nonatomic, assign) SSPhotosButtonText text;
- (void)setText:(SSPhotosButtonText)text;
#end
SSPhotosButton.m:
#import "SSPhotosButton.h"
#implementation SSPhotosButton
- (id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super initWithCoder:aDecoder]) {
self.layer.masksToBounds = YES;
if (self.text == SSPhotosButtonTextDownload) {
[self updateButtonWithText:#"Download"];
}
else if (self.text == SSPhotosButtonTextAdd) {
[self updateButtonWithText:#"Add"];
}
}
return self;
}
- (void)setText:(SSPhotosButtonText)text {
_text = text;
switch (text) {
case SSPhotosButtonTextDownload:
[self updateButtonWithText:#"Download"];
break;
case SSPhotosButtonTextAdd:
[self updateButtonWithText:#"Add"];
break;
default:
break;
}
}
- (void)updateButtonWithText:(NSString *)string {
self.titleLabel.text = string;
[self setTitle:string forState:UIControlStateNormal];
[self setBackgroundColor:[UIColor clearColor]];
[self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[self setTitleColor:[UIColor colorWithWhite:0.75 alpha:1.0] forState:UIControlStateHighlighted];
[self setTitleColor:[UIColor colorWithWhite:0.75 alpha:1.0] forState:UIControlStateSelected];
[self setTitleColor:[UIColor colorWithWhite:0.25 alpha:0.5] forState:UIControlStateDisabled];
}
#end
My problem is: No matter which button I select, (albumButton or galleryButton), the text is always "Download", never "Add". I suspect I'm doing something wrong in my SSPhotosButton classes, which is SSPhotosButtonText is always 0, which is why it's always SSPhotosButtonTextDownload, but how can I fix this?
Thank you.
In prepareForSeque you never instantiate the destination view controller directly. Instead, you access it via the segue parameter:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
SSPhotoSelectionViewController *controller = (SSPhotoSelectionViewController *) segue.destinationViewController;
if ([segue.identifier isEqualToString:#"SelectPhotosSegue"]) {
if (self.albumsButton.selected) {
[controller.downloadButton setText:SSPhotosButtonTextAdd];
}
else if (self.galleryButton.selected) {
[controller.downloadButton setText:SSPhotosButtonTextDownload];
}
}
}
Doing it so should set your text correctly.

Reload UIScrollView by tapping a UIButton

Let me explain my project first. I have some data in my SQLIte DB table called "note".
In "note" table I have these fields: id, noteToken, note.
What I am doing here is load all the note in an NSMUtableArray from that table. And create UIButton according to that array content number and add those buttons in a UIScrollView as subView. The number of buttons and width of scrollview generate auto according to the number of content of that array. Now, when some one tap one of those Buttons, it will bring him to a next viewController and show him the corresponding note details in that viewController.
I do the same thing with another NSMUtableArray, but these time it read all the id from the "note" table. It equally generate new delete button in the same UIScrollView. But if some one tap on these delete button it will delete that particular note from the table "note" of SQLIte DB. AND RELOAD THE UIScrollView. All are done except the RELOAD THE UIScrollView part. This is what I want. I tried with all exist solution but don't know why it's not working.
Here is my code:
- (void)viewDidLoad
{
[super viewDidLoad];
self.noteToken = [NSString stringWithFormat:#"%#%#", fairId, exibitorId];
scrollViewNoteWidth = 100;
[scrollViewNote setScrollEnabled:YES];
[scrollViewNote setContentSize:CGSizeMake((noteButtonWidth * countNoteButtonArray) + scrollViewNoteWidth, 100)];
sqLite = [[SQLite alloc] init];
[self.sqLite callDataBaseAndNoteTableMethods];
self.noteButtonArrayy = [[NSMutableArray alloc] init];
noteButtonArrayy = [self.sqLite returnDataFromNoteTable:noteToken];
[self LoadNoteButtonAndDeleteButton:noteButtonArrayy];
}
//////////////*----------------------- Note Section (Down) -----------------------*//////////////
-(void) LoadNoteButtonAndDeleteButton:(NSMutableArray *) noteButtonArray
{
sQLiteClass = [[SQLiteClass alloc] init];
noteButtonArrayToShowNoteButton = [[NSMutableArray alloc] init];
/*--------------- Load the noteButton & pass note (Down)---------------*/
for (int i = 0; i < [noteButtonArray count]; i++)
{
sQLiteClass = [noteButtonArray objectAtIndex:i];
// NSString *ids = [NSString stringWithFormat:#"%d", sQLiteClass.idNum];
NSString *nt = sQLiteClass.note;
[noteButtonArrayToShowNoteButton addObject:nt];
}
[self ShowNoteButtonMethod:noteButtonArrayToShowNoteButton];
/*--------------- Load the noteButton & pass note (Up)---------------*/
/*--------------- Load the deleteButton & pass id (Down)---------------*/
noteButtonArrayToDeleteNoteButton = [[NSMutableArray alloc] init];
for (int i = 0; i < [noteButtonArray count]; i++)
{
sQLiteClass = [noteButtonArray objectAtIndex:i];
// Convert int into NSString
NSString *ids = [NSString stringWithFormat:#"%d", sQLiteClass.idNum];
[noteButtonArrayToDeleteNoteButton addObject:ids];
}
[self ShowNoteDeleteButtonMethod:noteButtonArrayToDeleteNoteButton];
/*--------------- Load the deleteButton & pass id (Down)---------------*/
}
-(void) ShowNoteButtonMethod:(NSMutableArray *) btnarray
{
countNoteButtonArray = [btnarray count];
// For note button
noteButtonWidth = 60;
noteButtonXposition = 8;
for (NSString *urls in btnarray)
{
noteButtonXposition = [self addNoteButton:noteButtonXposition AndURL:urls];
}
}
-(int) addNoteButton:(int) xposition AndURL:(NSString *) urls
{
noteButton =[ButtonClass buttonWithType:UIButtonTypeCustom];
noteButton.frame = CGRectMake(noteButtonXposition, 8.0, noteButtonWidth, 60.0);
[noteButton setImage:[UIImage imageNamed:#"note.png"] forState:UIControlStateNormal];
[noteButton addTarget:self action:#selector(tapOnNoteButton:) forControlEvents:UIControlEventTouchUpInside];
[noteButton setUrl:urls];
noteButton.backgroundColor = [UIColor clearColor];
[self.scrollViewNote addSubview:noteButton];
noteButtonXposition = noteButtonXposition + noteButtonWidth + 18;
return noteButtonXposition;
}
-(void)tapOnNoteButton:(ButtonClass*)sender
{
urlNote = sender.url;
[self performSegueWithIdentifier:#"goToNoteDetailsViewController" sender:urlNote];
}
-(void) ShowNoteDeleteButtonMethod:(NSMutableArray *) btnarray
{
countNoteButtonArray = [btnarray count];
// For delete button
deleteNoteButtonWidth = 14;
deleteNoteButtonXposition = 31;
for (NSString *idNumber in btnarray)
{
deleteNoteButtonXposition = [self addDeleteButton:deleteNoteButtonXposition AndURL:idNumber];
}
}
-(int) addDeleteButton:(int) xposition AndURL:(NSString *) idNumber
{
deleteNoteButton =[ButtonClass buttonWithType:UIButtonTypeCustom];
deleteNoteButton.frame = CGRectMake(deleteNoteButtonXposition, 74.0, deleteNoteButtonWidth, 20.0);
[deleteNoteButton setImage:[UIImage imageNamed:#"delete.png"] forState:UIControlStateNormal];
[deleteNoteButton addTarget:self action:#selector(tapOnDeleteButton:) forControlEvents:UIControlEventTouchUpInside];
[deleteNoteButton setIdNum:idNumber];
deleteNoteButton.backgroundColor = [UIColor clearColor];
[self.scrollViewNote addSubview:deleteNoteButton];
deleteNoteButtonXposition = deleteNoteButtonXposition + deleteNoteButtonWidth + 65;
return deleteNoteButtonXposition;
}
-(void)tapOnDeleteButton:(ButtonClass*)sender
{
idNumb = sender.idNum;
[self.sqLite deleteData:[NSString stringWithFormat:#"DELETE FROM note WHERE id IS '%#'", idNumb]];
// NSLog(#"idNumb %#", idNumb);
//[self.view setNeedsDisplay];
//[self.view setNeedsLayout];
//[self LoadNoteButtonAndDeleteButton];
//[self viewDidLoad];
// if ([self isViewLoaded])
// {
// //self.view = Nil;
// //[self viewDidLoad];
// [self LoadNoteButtonAndDeleteButton];
// }
}
//////////////*----------------------- Note Section (Up) -----------------------*//////////////
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"goToNoteDetailsViewController"])
{
NoteDetailsViewController *noteDetailsViewController = [segue destinationViewController];
[noteDetailsViewController setUrl:sender];
}
}
Here's the screen shot:
Here we can feel the difference between UIScrollView and UICollectionView, however UICollectionView is made up of UIScrollView, UICollectionView can be reload and adjust its content accordingly, where UIScrollView can't.
Ok, now in your case, you've to reload (refresh) your scroll view, which is not possible as we can with UICollectionView or UITableView.
You've two options,
Best option (little tough) : replace UIScrollView with UICollectionView - will take some of your time, but better for reducing code complexity and good performance of your app.
Poor option (easy) : Stay as it with UIScrollView - when you want to reload, delete each subview from it, and then again show and load everything. Highly not recommended.
IMHO, you should go with best option.

UISegmentedControl won't change value

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;
}
}

Resources