好吧,所以作为序言,我几天前才开始学习原生 iOS,来自 Titanium。我有动态 UI(导航元素),将根据用户是否登录来创建。在下面的代码中,我了解如何创建按钮,但我无法设置按钮的背景图像,代码提示甚至没有给我该选项。如果我在 .h
文件中设置一个 IBOutlet 并将按钮分配给它,那么我就可以访问 setBackgroundImage
方法。如果我不知道最终将拥有多少个 navButton,我无法在 .h
文件中为每个按钮设置属性?
或者我是否以完全错误的方式处理这个问题?我应该创建一个单独的类来处理这个问题吗?正如你可能看出的那样,我有点迷失了。
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.iconArray = @[@"member-icon",@"join-icon",@"business-development-icon",@"referral-system-icon",@"apprenticeship-icon",@"links-icon",@"paydues-icon"];
//Find out how many views are in the iconArray
NSInteger numberOfViews = [self.iconArray count];
for (int i = 0; i < numberOfViews; i++) {
//create the sub view and allocate memory
UIView *navButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 102, 85)];
[self.navScroller addSubview:navButton];
}
}
最佳答案
我最初的想法是将 navButton 的类型声明从 UIView 更改为 UIButton。代码提示不会为您提供 setBackgroundImage:
方法,因为 UIView 没有,而这正是它要找的地方。
改变:
UIView *navButton ...
到:
UIButton *navButton ...
至于给每个按钮一个 Action ,我建议制作一个将发件人作为参数的方法。在您的 UIViewController 的某处创建此方法:
- (void)buttonPressed:(UIButton *)sender
{
if (sender.currentTitle isEqualToString:@"member-icon") {
// perform segue using segueIdentifier
}
else if (sender.currentTitle isEqualToString:@"...") {
// perform segue using segueIdentifier
}
// else if until all scenarios are covered
}
然后在您的 for 循环中,您需要执行类似于以下的操作:
// implement inside the for loop where the button is created
for (int i = 0; i < numberOfViews; i++) {
//create the sub view and allocate memory
UIButton *navButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 102, 85)];
[navButton setTitle:@"/*insert button title*/" forState:UIControlStateNormal];
[navButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.navScroller addSubview:navButton];
}
另一种方法是为每个按钮设置一个方法,并根据创建的按钮将方法添加为 action:
参数。希望这有助于...
关于ios - 如何在 iOS 代码中创建和访问 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19649513/