【问题标题】:How to Add and Remove UIButtons in SubView using UISilder?如何使用 UISilder 在 SubView 中添加和删除 UIButtons?
【发布时间】:2012-09-07 12:32:51
【问题描述】:

我有一个subview,它几乎占我主视图的一半,我的主视图上还有一个UISlider。我的 silder 的值从 0 到 10。我想用 UISilder 将一些 UIButtons 添加到我的 Subview。现在如果我的 silder 得到值 2,那么我想将 2 UIButtons 添加到我的Subview 好像我的 silder 传递值 2 并获得值 4 然后我想从 Subview 中删除以前的 UIButtons 并将一些新的 UIButtons 添加到 Subview 。

【问题讨论】:

    标签: objective-c ios cocoa-touch uibutton uislider


    【解决方案1】:

    注意:代码未经测试。

    1. 发起一个 10 UIButton 并将它们添加到视图中,将它们设置为隐藏:

      for (int x = 0; x < 10; x++) {
          UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(50, x * 100, 100, 50)];
          [btn setText:[NSString stringWithFormat:@"Button %d",(x + 1)]];
          [btn setHidden:true];
          [self.view addObject:btn];
          [btn release];
      }
      
    2. 使用滑块更改值的方法来隐藏/显示按钮,如下所示:

          -(IBAction) sliderChanged:(id) sender{
                UISlider *slider = (UISlider *) sender;
                for (int x = 0; x < slider.value; x++) {
                     UIButton *btn = (UIButton *)[savedBtn objectAtIndex:x];
                     [btn setHidden:false];
                }
          }
      

    更新

    要使用UIScrollView,您必须将UIButtons 添加到scrollView 而不是视图,如下所示:

        UIScrollView *sView = [[UIScrollView alloc] initWithFrame:CGRectMake(10,10,200,200)];
        [sView setDelegate:self];
        for (int x = 0; x < 10; x++) {
            UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(50, x * 100, 100, 50)];
            [btn setText:[NSString stringWithFormat:@"Button %d",(x + 1)]];
            [btn setHidden:true];
            [sView addSubview:btn];
            [btn release];
        }
    

    然后将scrollView添加到视图中:

         [self.view addSubview:sView];
    

    希望对您有所帮助。

    【讨论】:

    • Thanx @Scar 你的答案解决了我的基本问题。你能帮我更多关于滚动视图的信息吗,因为我的子视图有 100 高,所以为什么它只显示三个按钮和我的第四个按钮和第五个按钮按钮有 y.xis 130,150 所以请建议我如何解决这个问题。谢谢
    【解决方案2】:

    首先你添加一个选择器方法到你的UISlider

    [customSlider addTarget:selfaction:@selector(sliderEnd:)forControlEvents:UIControlEventTouchUpInside];
    

    现在应该在项目的Mainview 类中定义选择器方法。

    现在,在选择器方法中,您可以确定函数中的滑块值,并且根据其值,您可以向另一个视图添加或删除或添加按钮。您可以在将所有按钮添加到视图时存储对它们的引用,然后在滑块值建议时将它们从 superview 中删除。

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多