0

好的,所以以我几天前才真正开始学习原生iOS的事实作为开头,来自Titanium。我有动态 UI(导航元素),将根据用户是否登录来创建。在下面的代码中,我了解如何创建按钮,但我无法为按钮设置背景图像,代码提示甚至没有给我选项。如果我在将按钮分配给它的文件中设置了一个 IBOutlet .h,那么我可以访问该setBackgroundImage方法。.h如果我不知道最终将拥有多少个 navButton,我无法在文件中为每个按钮设置属性?

还是我以完全错误的方式处理这个问题?我应该创建一个单独的类来处理这个吗?你可能会说我有点迷路了。

- (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];


}

}
4

1 回答 1

1

我最初的想法是将导航按钮的类型声明从 UIView 更改为 UIButton。代码提示没有为您提供setBackgroundImage:方法,因为 UIView 没有方法,而这正是它正在寻找的地方。

改变:

UIView *navButton ...

至:

UIButton *navButton ...

至于给每个按钮一个动作,我建议制作一个将发送者作为参数的单一方法。在你的 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:根据正在创建的按钮添加该方法作为参数。希望这可以帮助...

于 2013-10-29T04:25:11.040 回答