OGeek|极客世界-中国程序员成长平台

标题: ios - 按钮标签不能在循环中使用动态值? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 11:31
标题: ios - 按钮标签不能在循环中使用动态值?

请检查我的代码:

for (i = 0; i < fifth_img.count; i++)
{
    UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
    aButton.frame     = CGRectMake(xCord, yCord + space,buttonWidth,buttonHeight);
    [aButton addTarget:self actionselector(whatever1 forControlEvents:UIControlEventTouchUpInside];
    [aButton setTitle:[NSString stringWithFormat"%d",(int)i] forState:UIControlStateNormal];
    aButton.titleLabel.font = [UIFont systemFontOfSize:0.0];

    aButton.tag = i;
    [aButton setBackgroundImage:[UIImage imageNamed:[fifth_img objectAtIndex:i]] forState:UIControlStateNormal];
    [seasonsScrollView addSubview:aButton];
    yCord += buttonHeight + space;
}
[seasonsScrollView setContentSize:CGSizeMake(Vu_leftPanel.frame.size.width, yCord)];
[Vu_leftPanel addSubview:seasonsScrollView];


for( int b=0; b<6; b++){
    [(UIButton *)[Vu_leftPanel viewWithTag:b] setBackgroundImage:[UIImage imageNamed:[fifth_img objectAtIndex:b]] forState:UIControlStateNormal];
}

当我将 5 或 3 或 1 放入 viewWithTag:5 时,它正在工作,但当我只放入 b 时,应用程序崩溃。



Best Answer-推荐答案


确保 Vu_leftPanel 没有任何其他标签在 0 到 6 之间的 View [因为 View 的默认标签是 0]。因为 setBackgroundImage:forState: 方法只能在 UIButton 上调用。 如果任何其他 View 收到此方法调用,则应用程序将崩溃,并将无法识别的选择器发送到实例异常。

尝试将标签从 1000 设置为 1006。然后尝试设置背景图像。

关于ios - 按钮标签不能在循环中使用动态值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31985190/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4