This is a beginner’s question about the fundamentals of objective programming (at least I think so..):
I have an UIView and would like to add several buttons to this UIView programatically. How many buttons there are depends on the user input.
Every button has four characteristics:
- Its number (e.g. button number one, two, three etc.)
- Its title (e.g. click this, click here, click me etc.)
- Its position and size (i.e. a CGRect – size stays the same, only y-position needs to change)
- Its colour (e.g. red, green, blue etc.)
Now I thought I can create a button by creating a method, but I am not entirely sure if this is a very sound method. I have the feeling that I should have created an object. Any help of how I should go about this would be very much appreciated. Here is my attempt – which is full of mistakes (for instance, I wasn’t sure of how to create button1, button2 etc. — hence the button[bNumber] thing):
-(void) createIndexButtonWithNumber:(NSString *)bNumber withTitle:(NSString *)bTitle atPosition:(NSInteger *)bPosition withColour:(NSInteger *)bColour {
CGRect buttonFrame = CGRectMake(0,bPosition,25,25);
UIButton* button[bNumber] = [[[UIButton alloc] initWithFrame:buttonFrame] autorelease];
UIButton.text = bTitle;
if (bColour == 1) {UIButton.color = [UIColor colorWithRed:0.751 green:0.742 blue:0.715 alpha:1.000];};
[indexView addSubview:button[bNumber]];
// to do: if button[bNumber] pressed {do something};
}
Then, I would like to ‘multiply’ the object three times by calling:
for (temp = 0; temp < 2; temp++) {
[self createIndexButtonWithNumber:temp withTitle:[@"Test%i", temp] atPosition:10 withColour:1];}
I’m sure this is all a bit problematic, wrong and clumsy, so I’d be very grateful for any suggestions of how to tackle this.
I’d like to reference to UIButton Class Reference
You should create buttons only with
buttonWithType:method.Second, there is no button color. You can set a color for title with
setTitleColor:forState:method.There are just syntax mistakes in your code (
UIButton.text, etc). You cant do such a call.UIButtonis a class.Your calling
createIndexButtonWithNumber...withinforwill place buttons in the same place —atPositioninput parameter has no change.NSIntegervariable is not a pointer —*is not needed.…
In the end of struggling we have smth like that:
-(void)createIndexButtonWithNumber:(NSInteger)bNumber//(sorry for that, some troubles with code formatting)And
forcall:UPDATE: Selector method