我需要以编程方式创建几个按钮和标签。大多数情况下,除文本,标签和框架外,它们都具有相同的属性(不透明,backgroundColor,textColor)。以编程方式创建元素并重新使用代码
虽然试图限制我需要键入的代码量,我想这会工作:
// generate generic properties for our buttons UIButton *tempButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; tempButton.opaque = true; tempButton.backgroundColor = [UIColor whiteColor]; tempButton.titleLabel.font = [UIFont fontWithName:@"Helvitica-Bold" size:15];; [tempButton setTitleColor:[UIColor magentaColor] forState:UIControlStateNormal]; [tempButton addTarget:self action:@selector(handleButtonTap:) forControlEvents:UIControlEventTouchUpInside]; // generate specific button1 properties, assign to ivar, and display tempButton.frame = CGRectMake(81, 136, 159, 37); tempButton.tag = BUTTON_1_TAG; [tempButton setTitle:@"button 1 title" forState:UIControlStateNormal]; self.button1 = tempButton; [self.view addSubview:self.button1]; // generate specific button2 properties, assign to ivar, and display tempButton.frame = CGRectMake(81, 254, 159, 37); tempButton.tag = BUTTON_2_TAG; [tempButton setTitle:@"button 2 title" forState:UIControlStateNormal]; self.button2 = tempButton; [self.view addSubview:self.button2];
由于大部分你已经知道,只有最后一个按钮显示。我认为这是因为我真的在做的是覆盖tempButton。
有没有一种解决方案可以让我完成我在这里要做的工作,而无需为每个元素创建单独的“temp”变量?
另外,它似乎会有我的代码上面的内存泄漏问题。我的理解是,tempButton最初是自动释放的,但每次我用它来设置我的伊娃时,是不是又被保留了下来?这样做后,我需要发送tempVar一个版本,所以它会回落到1,所以当autorelease被触发时,它实际上会被释放?
感谢您的帮助!
Ooh,viewForTag。我喜欢。使事情变得简单很多。你在上面的评论中提到了Cocoa命名约定。是否有一个标准的约定跟随标签,如果没有,你有你自己的? – djibouti33 2011-02-27 02:13:26
我认为你的意思是viewWithTag。找不到对viewForTag的任何引用。 – djibouti33 2011-02-27 08:37:58