【发布时间】:2011-07-05 02:10:55
【问题描述】:
我需要以编程方式创建几个按钮和标签。在大多数情况下,它们将具有相同的属性(不透明、背景颜色、文本颜色),但文本、标签和框架除外。
在尝试限制我需要输入的代码数量时,我认为这会起作用:
// 为我们的按钮生成通用属性 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]; // 生成具体的button1属性,赋值给ivar,并显示 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]; // 生成具体的button2属性,赋值给ivar,并显示 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。
有没有一种解决方案可以让我完成我在这里尝试做的事情,而不必为每个元素创建单独的“临时”变量?
另外,我上面的代码似乎存在内存泄漏问题。我的理解是 tempButton 最初是自动释放的,但是每次我用它来设置我的 ivar 时,它不是又被保留了吗?这样做之后,我是否需要向 tempVar 发送一个释放,使其回落到 1,这样当触发自动释放时,它实际上会被释放?
感谢您的帮助!
【问题讨论】:
标签: iphone objective-c ios memory-management