how to set multiple buttons in UIScrollView? - iphone

how to set multiple buttons in UIScrollView and also how to set clicked action for particular button index?

UIScrollView *view = ..;
UIButton *button1 = ... ;
button1.tag = 1;
UIButton *button2 = ... ;
button1.tag = 2;
UIButton *button3 = ... ;
button1.tag = 3;
[view addSubview:button1];
[view addSubview:button2];
[view addSubview:button3];
In IBAction method check button tag to identify clicked button.

you can call this(initScrollView) method on viewDidLoad
- (void)viewDidLoad {
arrayScrollViewImages = [[NSArray alloc] initWithObjects:
[[MyKeyValuePair alloc] initWithKey:#"imagename1" withValue:#"imagename1.png"],
[[MyKeyValuePair alloc] initWithKey:#"imagename2" withValue:#"imagename2.png"],nil];
[self initScrollView];
}
here arrayScrollViewImages is NSArray
- (void) initScrollView
{
int width = 10;
for (int index = 0; index < [arrayScrollViewImages count]; index++) {
MyKeyValuePair *pair = [arrayScrollViewImages objectAtIndex:index];
UIImage *image = [UIImage imageNamed:pair.value];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(width, 2, 34, 34)];
[button setBackgroundImage:image forState:UIControlStateNormal];
[button setTag:index];
[button addTarget:self action:#selector(scrollViewButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
if (index == 0) {
[button setBackgroundColor:[UIColor colorWithRed:0.59 green:0.38 blue:0.21 alpha:1.00]];
}
[scrollView addSubview:button];
width += 45;
}
scrollView.contentSize = CGSizeMake(width, 48);
scrollView.contentOffset = CGPointMake(0, 0);
}
- (void) scrollViewButtonTapped:(id)sender {
for (UIButton *b in scrollView.subviews) {
if ([b isKindOfClass:[UIButton class]]) {
[b setBackgroundColor:[UIColor clearColor]];
}
}
UIButton *button = (UIButton *) sender;
[button setBackgroundColor:[UIColor colorWithRed:0.59 green:0.38 blue:0.21 alpha:1.00]];
MyKeyValuePair *pair = [arrayScrollViewImages objectAtIndex:button.tag];
labelEspecialidad.text = pair.key;
}
here MyKeyValuePair is a one class
*MyKeyValuePair.h*
#interface MyKeyValuePair : NSObject {
NSString *key;
NSString *value;
}
// Properties
#property (nonatomic, retain) NSString *key;
#property (nonatomic, retain) NSString *value;
#end
MyKeyValuePair.m
#implementation MyKeyValuePair
#synthesize key, value;
- (id) initWithKey: (NSString *) _key withValue: (NSString *) _value {
if (self = [super init]) {
self.key = _key;
self.value = _value;
}
return self;
}
- (void) dealloc {
[super dealloc];
[self.key release];
[self.value release];
}
#end

Using XCode Interface Builder
Add buttons (select and drag&drop them from side objects panel)
Create IBAction for every button (in owner class .h and implement in .m)
Link buttons to actions via right mouse click&drag
See some video tutorials on youtube, such as
http://www.youtube.com/watch?v=WgAAvRQBrPc
http://www.youtube.com/watch?v=uAdmetwz7sc
http://www.youtube.com/watch?v=vixD-N6cbDY
and read Developer Guide
http://www.switchonthecode.com/tutorials/creating-your-first-iphone-application-with-interface-builder
http://developer.apple.com/library/ios/#documentation/IDEs/Conceptual/Xcode4TransitionGuide/InterfaceBuilder/InterfaceBuilder.html

You can use an array of buttons for that purpose. Assign a unique tag id to each button, and programmatically spread the buttons along the UIScrollView. Have the UIScrollView listen to the Touch Up Inside event, where you can then determine which button has been clicked by the unique tag ID.

Related

Create new UI elements programmatically

I'd like to be able to create elements (like UIViews) when for example the user touches a button
NSMutableString *myVar = [NSMutableString stringWithFormat:#"_view%i", num];
UIView * newView = [self valueForKey:myVar];
but without adding all the
UIView * _view1;
UIView * _view2;
...
in the .h file (if only this is possible..)
You can use an NSMutableArray to hold them. Each time you create a new view just add it to the array.
Here's sample code that should do what you want.
#interface MyViewController ()
#property (strong, nonatomic) NSMutableArray *listChildViews;
#end
#implementation MyViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.listChildViews = [[NSMutableArray alloc] init];
}
- (IBAction)addChildViewTapped:(id)sender
{
int numChildViews = [self.listChildViews count];
++numChildViews;
// add new child view
NSString *labelForNewView = [NSString stringWithFormat:#"view %d", numChildViews];
CGFloat labelHeight = 28.0;
UILabel *childView = [[UILabel alloc] initWithFrame:CGRectMake(10, numChildViews*labelHeight, 120.0, labelHeight)];
childView.text = labelForNewView;
[self.listChildViews addObject:childView];
[self.view addSubview:childView];
}
#end
Here is code implementation of pauls answer:
- (IBAction)userTouchedButton:(id)sender{
for (int i = 0; i < 100; i++) {
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
[view setBackgroundColor:[UIColor redColor]];//to distinguish theseViews from other views
[view setTag:i];//to identified it later
[_array insertObject:view atIndex:i];// globleMutble array
[self.view addSubview:view];
}
}
You need not add your views in the .h file. Just instantiate before and where you add them
-(void) addButton
{
UIView *view = [self view];
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button1 setTitle:#"My Button" forState:UIControlStateNormal];
UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 50, 0, 0)];
[myLabel setText:#"My Label"];
[button1 sizeToFit];
[myLabel sizeToFit];
[view addSubview:button1];
[view addSubview:myLabel];
}

default selection on custom Radio Button in iphone

I want to implement radio buttons in my app
I used https://www.cocoacontrols.com/controls/radiobutton (cocoa controls Radio Buttons) .
I want that one of them should always be selected by default. how can I achive this .
My Radio button code is as follows:
RadioButton *radioButtonForDay = [[RadioButton alloc] initWithGroupId:#"first group" index:0 ];
RadioButton *radioButtonForWeek = [[RadioButton alloc] initWithGroupId:#"first group" index:1 ];
RadioButton *radioButtonForMonth = [[RadioButton alloc] initWithGroupId:#"first group" index:2 ];
radioButtonForDay.frame = CGRectMake(40,65,22,28);
radioButtonForWeek.frame = CGRectMake(130,65,22,28);
radioButtonForMonth.frame = CGRectMake(195,65,22,28);
[self.view addSubview:radioButtonForDay];
[self.view addSubview:radioButtonForWeek];
[self.view addSubview:radioButtonForMonth];
[RadioButton addObserverForGroupId:#"first group" observer:self];
RadioButton.m
`
import "RadioButton.h"
#interface RadioButton()
-(void)defaultInit;
-(void)otherButtonSelected:(id)sender;
-(void)handleButtonTap:(id)sender;
#end
#implementation RadioButton
#synthesize groupId=_groupId;
#synthesize index=_index;
static const NSUInteger kRadioButtonWidth=22;
static const NSUInteger kRadioButtonHeight=22;
static NSMutableArray *rb_instances=nil;
static NSMutableDictionary *rb_observers=nil;
pragma mark - Observer
+(void)addObserverForGroupId:(NSString*)groupId observer:(id)observer{
if(!rb_observers){
rb_observers = [[NSMutableDictionary alloc] init];
}
if ([groupId length] > 0 && observer) {
[rb_observers setObject:observer forKey:groupId];
// Make it weak reference
//[observer release];
}
}
pragma mark - Manage Instances
+(void)registerInstance:(RadioButton*)radioButton{
if(!rb_instances){
rb_instances = [[NSMutableArray alloc] init];
}
[rb_instances addObject:radioButton];
// Make it weak reference
//[radioButton release];
}
pragma mark - Class level handler
+(void)buttonSelected:(RadioButton*)radioButton{
// Notify observers
if (rb_observers) {
id observer= [rb_observers objectForKey:radioButton.groupId];
if(observer && [observer respondsToSelector:#selector(radioButtonSelectedAtIndex:inGroup:)]){
[observer radioButtonSelectedAtIndex:radioButton.index inGroup:radioButton.groupId];
}
}
// Unselect the other radio buttons
if (rb_instances) {
for (int i = 0; i < [rb_instances count]; i++) {
RadioButton *button = [rb_instances objectAtIndex:i];
if (![button isEqual:radioButton] && [button.groupId isEqualToString:radioButton.groupId]) {
[button otherButtonSelected:radioButton];
}
}
}
}
pragma mark - Object Lifecycle
-(id)initWithGroupId:(NSString*)groupId index:(NSUInteger)index {
self = [super init];
if (self) {
_groupId = groupId;
_index = index;
// _selected = selected;
[self defaultInit];
}
return self;
}
(void)dealloc
{
//[_groupId release];
// [_button release];
// [super dealloc];
}
pragma mark - Tap handling
-(void)handleButtonTap:(id)sender{
[_button setSelected:YES];
[RadioButton buttonSelected:self];
}
-(void)otherButtonSelected:(id)sender{
// Called when other radio button instance got selected
if(_button.selected){
[_button setSelected:NO];
}
}
pragma mark - RadioButton init
-(void)defaultInit{
// Setup container view
self.frame = CGRectMake(0, 0, kRadioButtonWidth, kRadioButtonHeight);
// Customize UIButton
_button = [UIButton buttonWithType:UIButtonTypeCustom];
_button.frame = CGRectMake(0, 0,kRadioButtonWidth, kRadioButtonHeight);
_button.adjustsImageWhenHighlighted = NO;
[_button setImage:[UIImage imageNamed:#"RadioButton-Unselected"] forState:UIControlStateNormal];
[_button setImage:[UIImage imageNamed:#"RadioButton-Selected"] forState:UIControlStateSelected];
[_button addTarget:self action:#selector(handleButtonTap:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:_button];
[RadioButton registerInstance:self];
}
#end
`
Initially set selected image to any of your button.
[yourBtn setImage:yourImage forState:UIControlStateNormal];
And according to your code just put handleButtonTap method in RadioButton.h
-(void)handleButtonTap:(id)sender;
and in RadioButtonViewController.m
access the button which you want to select
Its for second button (i.e. RadioButton *rb2)
for (id subView in [rb2 subviews]) {
if ([subView isKindOfClass:[UIButton class]]) {
[rb2 handleButtonTap:subView];
}
}
Try this :
for default selection
[btnR setImage:[UIImage imageNamed:#"btnCheck.png"] forState:UIControlStateNormal];
[btnG setImage:[UIImage imageNamed:#"btnUnCheck.png"] forState:UIControlStateNormal];
[btnB setImage:[UIImage imageNamed:#"btnUnCheck.png"] forState:UIControlStateNormal];
and when you go to next view just check condition....
UIImage* selectedImg=[UIImage imageNamed:#"btnCheck.png"]; //btnCheck.png your image name
if (btnR.imageView.image == selectedImg || btnG.imageView.image == selectedImg || btnB.imageView.image == selectedImg)
{
//One of them is selected
}
else {
NSLog(#"Please Select At least One Color" );
}

NSMutableArray UIButtons Action?

I am Creating UIButtons programmatically and Then Store these UIButtons in NSMutableArray. All these UIButtons have Some Text as Titles. I have No Outlet for These UIButtons. Now I want to Assign the Title of UIButton to UIlabel when I touch or Click some UIButton. But the problem for me is this: how can I perform the function on these UIButtons. Because I created UIButtons programmatically and also these UIButtons have No Outlet. Here is my code to create Buttons:
saveBtn = [[NSMutableArray alloc] init];
for (int i=0; i<30; i++) {
if (btnn>8) {
UIButton *btn = [UIButton
buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(200.0 , spacey, 30.0, 30.0);
int idx;
idx = arc4random()%[arr count];
NSString* titre1 = [arr objectAtIndex:idx];
[btn setTitle:titre1 forState:UIControlStateNormal];
spacey=spacey+30;
spacex = 80;
btnn = 0;
}
else {
btnn++ ;
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(spacex, spacey, 30.0, 30.0);
int idx;
idx = arc4random()%[arr count];
NSString* titre1 = [arr objectAtIndex:idx];
[btn setTitle:titre1 forState:UIControlStateNormal];
spacex = spacex + 30;
[saveBtn addObject:btn];
[self.view addSubview:btn];
}
}
Please any one can guide me how can perfom action for these NSMutableArray UIButtons.
You can add actions to an UIButton programmatically using:
[button addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
- (void)buttonClicked:(UIButton *)btn
{
[btn setTitle:#"UnAutreTitre" forState:UIControlStateNormal];
}
Hope this helps.
Simply set tag and add target to the button. Later, you can get which button was tapped.
Create the action for the UIButton action, where you will be sending the (id)sender to the actionButtonFunction.
Assign sender to UIButton and then take the button title in NSString.
-(UIAction)buttonAction:(id)sender
{
UIButton *button = (UIButton *)sender;
NSString *buttonTitle = button.text;
// further code goes here
}

Custom search results button has weird behaviour in UISearchBar

I subclassed UISearchBar in order to set custom image to search results button the following way (.m file):
#import "CustomUISearchBar.h"
#define RGB(r, g, b) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1]
#define RGBA(r, g, b, a) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a]
#implementation GipUISearchBar
- (void)layoutSubviews
{
UITextField *searchField = nil;
UIView *backGround = nil;
UIButton *cancelButton = nil;
NSUInteger numViews = [self.subviews count];
for(int i = 0; i < numViews; i++)
{
if([[self.subviews objectAtIndex:i] isKindOfClass:[UITextField class]])
{
searchField = [self.subviews objectAtIndex:i];
}
else if ([[self.subviews objectAtIndex:i] isKindOfClass:NSClassFromString(#"UISearchBarBackground")])
{
backGround = [self.subviews objectAtIndex:i];
}
else if ([[self.subviews objectAtIndex:i] isKindOfClass:[UIButton class]])
{
cancelButton = [self.subviews objectAtIndex:i]; [cancelButton setTintColor:RGB(22.0,38.0,111.0)];
}
}
if(!(searchField == nil))
{
searchField.layer.cornerRadius=15.0f;
searchField.layer.masksToBounds=YES;
searchField.layer.borderColor = [RGB(26.0,141.0,223.0)CGColor];
searchField.layer.borderWidth = 2.0f;
UIImage *glassImage = [UIImage imageNamed: #"search_icon.png"];
UIImageView *iView = [[UIImageView alloc] initWithImage:glassImage];
searchField.leftView = iView;
[iView release];
UIImage *historyImage = [UIImage imageNamed:#"history_button.png"];
UIButton *historyButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[historyButton setBackgroundImage:historyImage forState:UIControlStateNormal];
[historyButton setBackgroundImage:historyImage forState:UIControlStateSelected];
[historyButton setBackgroundImage:historyImage forState:UIControlStateDisabled];
[historyButton setBackgroundImage:historyImage forState:UIControlStateHighlighted];
historyButton.frame = CGRectMake(0,
0,
historyImage.size.width-3,
historyImage.size.height-3);
historyButton.layer.borderColor = [RGBA(0.0,0.0,0.0,0.0)CGColor];
historyButton.layer.borderWidth = 0.0f;
searchField.rightView = historyButton;
}
if (!(backGround == nil))
[backGround removeFromSuperview];
[super layoutSubviews];
}
The problem is when i touch inside search bar and it resizes i see this button being moved from left to right. How can i disable this behaviour?
try commenting below lines.
[super layoutSubviews];
Because it seems that you are overriding layout of UISearchBar by inheriting it.

Forward event from custom UIControl subclass

My custom subclass extend UIControl (EditableImageView)
Basically it contains 3 subviews:
UIButton (UIButtonTypeCustom)
UIImageView
UILabel
All the class works great but now I want to connect some events generated from this class to another. In particular when the button is pressed I want to forward the event to the owner viewcontroller so that I can handle the event. The problem is that I can't figure out how to implement this behaviour.
Within EditableImageView I can catch the touch event using [button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside] but I don't know how to forward it inside of the buttonPressed selector.
I also tried to implement touchesBegan but it seems never called...
I'd like to capture the button press event from the viewcontroller in this way:
- (void)viewDidLoad {
[super viewDidLoad];
self.imageButton = [[EditableImageView alloc] initWithFrame:CGRectMake(50.0f, 50.0f, 80.0f, 80.0f)];
[imageButton addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:imageButton];
[imageButton setEditing:NO];
}
This is my UIControl subclass initialization method:
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
[self setBackgroundColor:[UIColor clearColor]];
button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0.0f, 0.0f, frame.size.width, frame.size.height);
[button setImage:[UIImage imageNamed:#"nene_70x70.png"] forState:UIControlStateNormal];
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:button];
transparentLabelBackground = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"editLabelBackground.png"]];
transparentLabelBackground.hidden = YES;
[self addSubview:transparentLabelBackground];
// create edit status label
editLabel = [[UILabel alloc] initWithFrame:CGRectZero];
editLabel.hidden = YES;
editLabel.userInteractionEnabled = NO; // without this assignment the button will not be clickable
editLabel.textColor = [UIColor whiteColor];
editLabel.backgroundColor = [UIColor clearColor];
editLabel.textAlignment = UITextAlignmentLeft;
UIFont *labelFont = [UIFont systemFontOfSize:16.0];
editLabel.font = labelFont;
editLabel.text = #"edit";
labelSize = [#"edit" sizeWithFont:labelFont];
[self addSubview:editLabel];
}
return self;
}
Thanks.
I solved in this way:
EditableImageView.h:
#interface EditableImageView : UIControl {
UIButton *button;
UIImageView *transparentLabelBackground;
UILabel *editLabel;
CGSize labelSize;
BOOL editing;
}
#property (nonatomic, retain) UIButton *button;
#property (nonatomic, retain) UILabel *editLabel;
#property (nonatomic, retain) UIImageView *transparentLabelBackground;
#property (nonatomic, getter=isEditing) BOOL editing;
- (void)buttonPressed:(id)sender;
#end
EditableImageView.m:
(id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
[self setBackgroundColor:[UIColor clearColor]];
button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0.0f, 0.0f, frame.size.width, frame.size.height);
[button setImage:[UIImage imageNamed:#"nene_70x70.png"] forState:UIControlStateNormal];
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
.......
}
}
- (void)buttonPressed:(id)sender {
[self sendActionsForControlEvents:UIControlEventTouchUpInside];
}
MyController.m:
- (void)viewDidLoad {
[super viewDidLoad];
self.imageButton = [[EditableImageView alloc] initWithFrame:CGRectMake(50.0f, 50.0f, 80.0f, 80.0f)];
[imageButton addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:imageButton];
}
- (void)buttonPressed:(id)sender {
NSLog(#"buttonPressed!");
}