ios - 创建多个 UIButtons 但只有最后一个可见

标签 ios

我正在 UIView 中创建多个 UIButton。有两个嵌套循环,以创建具有不同形状的不同按钮组。问题是,只有最后创建的 UIButton 是可见的(并且可以使用 PanGestureRecognizer 移动),即使按钮应该插入不同的位置也是如此。

- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view.

    int i, j;
    NSMutableString *backgoundImageName = [[NSMutableString alloc] init];
    NSMutableString *barTitle = [[NSMutableString alloc] init];
    sticks = [[NSMutableArray alloc] init];

    [mainView setBackgroundColor:[UIColor blackColor]];
    self.view = mainView;
    [mainView setNeedsDisplay];

    //create the bars
    UIButton *barra = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
    [barra addTarget:self action:@selector(changeButtonTitle:) forControlEvents:UIControlEventTouchUpInside];
    [barra addGestureRecognizer:panGestureRecognizer];
    for (j = 1; j <= 10; j++) {
        backgoundImageName = [NSMutableString stringWithFormat:@"Regolo%d%@",j,@".png"];
        for (i = 1; i <= 3; i++) {
            barra.frame = CGRectMake((SQUARE_SIZE * j), (SQUARE_SIZE * 2), SQUARE_SIZE, (SQUARE_SIZE * j));
            [barra setBackgroundImage:[UIImage imageNamed:backgoundImageName] forState:UIControlStateNormal];
            [barra setTag:j];

            barTitle = [NSMutableString stringWithFormat:@"%d",j];
            [barra setTitle:barTitle forState:UIControlStateNormal];
            [barra setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [sticks addObject:barra];
            [self.mainView addSubview:(UIButton *)sticks.lastObject];
        }
    }
}

最佳答案

移动这段代码:

UIButton *barra = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
[barra addTarget:self action:@selector(changeButtonTitle:) forControlEvents:UIControlEventTouchUpInside]; 
[barra addGestureRecognizer:panGestureRecognizer]; 

在你的内部 for 循环中。

您有一个对象 (UIButton *barra),您在一个循环中更改其属性,所以我认为最后所有按钮都堆叠在最后一个按钮的框架位置(以及最终背景,标题, 以及标记值), 只有最上面的是可见的。

关于ios - 创建多个 UIButtons 但只有最后一个可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12353378/

相关文章:

ios - UITableViewCell iOS 静态单元格的动画高度

ios - 是否可以通过 API 在 iOS 应用程序中创建可嵌入的推文,而无需用户登录 Twitter?

ios - 当 View 包含 UICollectionView 时,在 UITextField 之外的任何地方隐藏触摸键盘

ios - 在 Xcode 9 的上下文中,“对象”对于类型查找是不明确的

ios - 如何在 iOS 上首次编译 DCMTK?

ios - 解析 : change a pointer's value

ios - 快速播放一系列 MIDI 音符

iphone - 我如何检查 NSUrl 是否是有效的图像 url?

ios - 如何在swift中禁用导航 Controller 向右滑动

ios - 如果我为 iOS 4.3 构建了我的应用程序,它会在装有 OS 4.2 的设备上运行吗?