I am using the following code to create a custom switch:
UISegmentedControl* switchView=[[UISegmentedControl alloc]
initWithItems:[[NSMutableArray alloc] initWithObjects:#"On",#"Off",nil]];
[switchView setFrame:CGRectMake(20,365,140,28)];
switchView.selectedSegmentIndex=0;
switchView.segmentedControlStyle=UISegmentedControlStyleBar;
[switchView setImage:[UIImage imageNamed:#"onSelected.png"] forSegmentAtIndex:0];
[switchView setImage:[UIImage imageNamed:#"off.png"] forSegmentAtIndex:1];
[switchView addTarget:self action:#selector(checkOnOffState:) forControlEvents:UIControlEventValueChanged];
I would now like to add this control to one of my screens (I believe the correct term is ViewController?). How would I do this in Xcode 4.3?
I looked at a few other posts and was not able to find anything that works. For example, How do I add a custom view to iPhone app's UI? suggested something along the lines of
[[myVC view] addSubview:myView];
and How to customize UISwitch button in iphone? suggested
self.navigationItem.titleView=switchView;
If possible, could you also explain why these approaches did not work? Thanks.
You need to create a class for your switch which is subclass of your UISegmentControl ,
Else you can add this code in your vc directly as well.
Add this code in its initWithFrame method
and then use it in your VC
-(void)viewDidLoad{
urCustomSwitch = [urCustomSwitch alloc] initWithFrame:CGRectMake(20,365,140,28)];
[self.view addSubview:urCustomSwitch];
}
This shall serve your purpose if you are to create custom reusable class.
If you add this switch control i.e. UISegmentedControl in InterfaceBuilder (.xib file)
This task will be much easier for you.
Related
I'm updating some old code, and to make more room in a toolbar, I'm converting the Buttons from test to images. An example of the new and old code in loadView is this:
// New code, doesn't work.
UIButton *toggleKeyboardBtn = [UIButton buttonWithType:UIButtonTypeCustom];
toggleKeyboardBtn.bounds = CGRectMake( 0, 0, showKeyboardImage.size.width, showKeyboardImage.size.height );
[toggleKeyboardBtn setImage:showKeyboardImage forState:UIControlStateNormal];
UIBarButtonItem *toggleKeyboardItem = [[UIBarButtonItem alloc] initWithCustomView:toggleKeyboardBtn];
[toggleKeyboardItem setTarget:self];
[toggleKeyboardItem setAction:#selector(toggleKeyboard:)];
// Original code, works jut fine.
UIBarButtonItem *setupItem = [[[UIBarButtonItem alloc] initWithTitle:#"Setup" style:UIBarButtonItemStyleBordered target:[UIApplication sharedApplication].delegate action:#selector(showSetupView:)] autorelease];
My new code is copied from Cannot set action on UIBarButtonItem, and I'm fairly certain that I'm not making their mistake since my text button is working just fine.
showSetupView() is in my AppController.m file, and the setup screen appears and disappears as the button is pressed.
toggleKeyboard(), OTOH, is in the same file as the loadView() routine, and currently consists of this code:
//- (void)toggleKeyboard {
- (IBAction)toggleKeyboard:(id)sender {
NSLog(#"Entering toggleKeyboard()...");
hiddenKeyboard = !hiddenKeyboard;
[self prepareToolbarsAndStatusbar];
}
Needless to say, although I see the button-press animation, I never see the NSLog message. And one last observation, made by accident. Changing the setAction selector to this:
[toggleKeyboardItem setAction:#selector(noSuchRoutine:)];
compiles cleanly, possibly indicating that my routine name is being ignored for some reason.
Anyone have any ideas? Thanks.
I found the answer! In button action not responding iphone, it's said that the action and target need to be set on the UIButton, not the UIBarButtonItem. I don't know if that's new with the latest version of Xcode, but I guess it is since other questions (such as the one I mention above) use a different technique. Here's my new code:
UIButton *toggleKeyboardButton = [UIButton buttonWithType:UIButtonTypeCustom];
toggleKeyboardButton.bounds = CGRectMake( 0, 0, keyboardAddImage.size.width, keyboardAddImage.size.height );
[toggleKeyboardButton setImage:keyboardAddImage forState:UIControlStateNormal];
[toggleKeyboardButton addTarget:self action:#selector(toggleKeyboard) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *toggleKeyboardItem = [[UIBarButtonItem alloc] initWithCustomView:toggleKeyboardButton];
//[toggleKeyboardItem setTarget:self];
//[toggleKeyboardItem setAction:#selector(toggleKeyboard:)];
Though its too late, but for future references, I would like to quote apple docs for the method,
- (instancetype)initWithCustomView:(UIView *)customView;
The bar button item created by this method does not call
the action method of its target in response to user interactions.
Instead, the bar button item expects the specified custom view to
handle any user interactions and provide an appropriate response.
Did you try
-(void)toggleKeyboard
and
[toggleKeyboardItem setAction:#selector(toggleKeyboard)]; without :
and it made any difference? Is the method declared in the interface file?
I'm sure this is an easy one for someone out there. I have a UISegmentedControl which I am using as a button (so as not to have to use the nasty default button) and I am having trouble getting the target to work....code as follows
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
//read.buttonType = UIBarStyleBlackOpaque;
UISegmentedControl* read = [[[UISegmentedControl alloc] initWithFrame:CGRectMake(5, 50, 310, 54)] autorelease];
[read insertSegmentWithTitle:#"Read" atIndex:0 animated:NO];
read.tintColor = [UIColor colorWithRed:0.3 green:0.3 blue:0.9 alpha:1];
read.segmentedControlStyle = UISegmentedControlStyleBar;
[read addTarget:self action:#selector(changeFilter:sender:) forControlEvents:UIControlEventTouchUpInside];
[read setTag:1];
[self.view addSubview:read];
}
and then
-(void)changeFilter:(id)sender{
}
for some reason, clicking on the UISegmentedControl does not fire the target method.
As an addendum, is there a simpler way to make nice looking UIButtons? I don't have access to Photoshop at work (although I do have gimp installed), so a way which doesn't involve image making would be good. I can't believe that apple didn't supply nice looking UIButtons in the UI, it seems such a fundamental thing to need?
Anyway, thanks for the help mis amigos.
thanks for the answers...I've tried the fix but it still doesn't fire
I now have
[read addTarget:self action:#selector(changeFilter:) forControlEvents:UIControlEventTouchUpInside];
then
#interface
-(void)changeFilter:(id)sender;
and
#implementation
-(void)changeFilter:(id)sender{}
Note that the method is in the same class as the UISegmentedControl. Maybe I should just try using the Glass button API which was suggested, but my boss hates me using third party libraries if there is a way of avoiding it!
The selector is wrong. It should be, action:#selector(changeFilter:), And change the event to forControlEvents:UIControlEventValueChanged, as UISegmentedControl doesn't send any actions for UIControlEventTouchUpInside event.
.h file u forgot to put this
-(void)changeFilter:(id)sender;
then
change this
[read addTarget:self action:#selector(changeFilter:sender:) forControlEvents:UIControlEventTouchUpInside];
To
[read addTarget:self action:#selector(changeFilter:) forControlEvents:UIControlEventValueChanged];
The action will automatically send the sender so just try #selector(changeFilter:).
As for your second question, ios5 will help you out there... but I can't say much about that yet. For now, you can use some uibutton classes that people have made to easily make some good looking buttons. Here's one:
http://hboon.com/glass-buttons-in-iphone-apps-without-using-image-files/
I have added a UISegmented control as follows (this seems to work just fine, but let me know if this is a bad practice):
mapType = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects: #"Map", #"Satelitte", #"Hybrid", nil]];
[_mapView addSubview:mapType];
Then I have a method that I would like to be called when this UISegmentedControl is changed, however, I cannot set the delegate or anything in the interface builder because I am doing this programmatically.
- (void)segmentedChangedType {
// some code here
}
How can I connect these? Thanks in advance for any help!
If the only solution is to use XIB, then I can do that, but would like to know how to do this if it's possible.
OK, figured it out, you add this:
[mapType addTarget:self action:#selector(changeType) forControlEvents:UIControlEventValueChanged];
I would like to ask if there are examples out there on how to implement radio-button options on an iPhone app.
I find the Picker View quite big for a simple selection feature.
I'm not sure if Apple excluded radio buttons on purpose, and whether if it is better to simply use a Picker View from a usability / user experience point-of-view.
I have some thoughts on how the best radio button implementation should look like. It can be based on UIButton class and use it's 'selected' state to indicate one from the group. The UIButton has native customisation options in IB, so it is convenient to design XIBs.
Also there should be an easy way to group buttons using IB outlet connections:
I have implemented my ideas in this RadioButton class. Works like a charm:
Download the sample project.
Try UISegmentedControl. It behaves similarly to radio buttons -- presents an array of choices and lets the user pick 1.
Just want to sum up, there might be 4 ways.
If you don't have much space, add a click event for text or button, then show UIPickerView:
or open a new table view control with a check mark:
If there is more space, add a table view directly to your main view:
The final solution is using UISegmentedControl:
Hope this helps.
Try DLRadioButton, works for both Swift and ObjC. You can also use images to indicate selection status or customize your own style.
Check it out at GitHub.
**Update: added the option for putting selection indicator on the right side.
**Update: added square button, IBDesignable, improved performance.
**Update: added multiple selection support.
I know its very late to answer this but hope this may help anyone.
you can create button like radio button using IBOutletCollection. create one IBOutletCollection property in our .h file.
#property (nonatomic, strong) IBOutletCollection(UIButton) NSArray *ButtonArray;
connect all button with this IBOutletCollection and make one IBAction method for all three button.
- (IBAction)btnTapped:(id)sender {
for ( int i=0; i < [self.ButtonArray count]; i++) {
[[self.ButtonArray objectAtIndex:i] setImage:[UIImage
imageNamed:#"radio-off.png"]
forState:UIControlStateNormal];
}
[sender setImage:[UIImage imageNamed:#"radio-on.png"]
forState:UIControlStateNormal];
}
For options screens, especially where there are multiple radio groups, I like to use a grouped table view. Each group is a radio group and each cell a choice within the group. It is trivial to use the accessory view of a cell for a check mark indicating which option you want.
If only UIPickerView could be made just a little smaller or their gradients were a bit better suited to tiling two to a page...
I've written a controller for handling the logic behind an array of radio buttons. It's open source and on GitHub, check it out!
https://github.com/goosoftware/GSRadioButtonSetController
The following simple way to create radio button in your iOS app follow two steps.
Step1- Put this code in your in viewDidLoad or any other desired method
[_mrRadio setSelected:YES];
[_mrRadio setTag:1];
[_msRadio setTag:1];
[_mrRadio setBackgroundImage:[UIImage imageNamed:#"radiodselect_white.png"] forState:UIControlStateNormal];
[_mrRadio setBackgroundImage:[UIImage imageNamed:#"radioselect_white.png"] forState:UIControlStateSelected];
[_mrRadio addTarget:self action:#selector(radioButtonSelected:) forControlEvents:UIControlEventTouchUpInside];
[_msRadio setBackgroundImage:[UIImage imageNamed:#"radiodselect_white.png"] forState:UIControlStateNormal];
[_msRadio setBackgroundImage:[UIImage imageNamed:#"radioselect_white.png"] forState:UIControlStateSelected];
[_msRadio addTarget:self action:#selector(radioButtonSelected:) forControlEvents:UIControlEventTouchUpInside];
Step2- Put following IBAction method in your class
-(void)radioButtonSelected:(id)sender
{
switch ([sender tag ]) {
case 1:
if ([_mrRadio isSelected]==YES) {
// [_mrRadio setSelected:NO];
// [_msRadio setSelected:YES];
genderType = #"1";
}
else
{
[_mrRadio setSelected:YES];
[_msRadio setSelected:NO];
genderType = #"1";
}
break;
case 2:
if ([_msRadio isSelected]==YES) {
// [_msRadio setSelected:NO];
// [_mrRadio setSelected:YES];
genderType = #"2";
}
else
{
[_msRadio setSelected:YES];
[_mrRadio setSelected:NO];
genderType = #"2";
}
break;
default:
break;
}
}
I'm creating a small iPhone app, when application lauches, it will ask the user to sign up or Login. If they choose sign up safari will open. This part is done.
////button code
button = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
button.frame = CGRectMake(10, 150, 300, 50);
[button setTitle:#"Login" forState:UIControlStateNormal];
button.backgroundColor = [UIColor clearColor];
[button addTarget:self action:#selector(myaction:) forControlEvents:UIControlEventTouchUpInside];
button.adjustsImageWhenHighlighted = YES;
[mainView addSubview:button];
[button release];
If they click Login -
How to navigate to next window asking for username / password ? Can I do it button action ?
2.How I will store their info in plist ( if i'm correct ) ?
Thanks in advance.
One way to do (1.) is:
define a LoginViewController class that inherits from UIViewController
create a nib file named "login" with the UI elements for your login view
make your login button action do somehting like:
LoginViewController *controller = [[LoginViewController alloc] initWithNibName:#"login" bundle:nil];
[self presentModalViewController:controller animated:NO];
There are really several different questions here disguised as one.
1: in the method -buttonAction is where your navigation logic will be. It looks like you're probably working from xibs out of Interface Builder
2: You'll need to use the NSDictionary method called -writeToFile:atomically:. The arguments are the path string for the file to be stored on flash memory, and a BOOL YES/NO value that determines if the file is written immediately, or if it checks for errors first. I'd recommend setting atomically: to YES.
I'm gathering from your question that you're not familiar with Cocoa and UIKit. You'll be hard pressed to get a tutorial on how to put your application together. You're going to need to try Google for swapping views and handling page navigation. It's a lot deeper than what I'm describing here.