0

我想在另一个下方添加按钮。我有这个简单的代码:

- (void)viewDidLoad
{
    [super viewDidLoad];

    for(int i=0 ; i<9 ; i++)
    {
        UIButton *myButton = [[UIButton alloc] init];
        myButton.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height/10); //this "10" i want also dynamically
        myButton.backgroundColor = [UIColor blackColor];
        [self.view addSubview:myButton];
    }

}

我当然知道它会一个接一个。但是我可以在不知道高度的情况下在循环中执行它吗(因为高将取决于循环中有多少按钮)。

我想要达到的目标:

纽扣

4

3 回答 3

1

试试这个:

- (void)viewDidLoad
  {
    [super viewDidLoad];
    int number = 10;

     for(int i=0 ; i<9 ; i++)
    {
    UIButton *myButton = [[UIButton alloc] init];
    myButton.frame = CGRectMake(self.view.frame.origin.x, (self.view.frame.size.height/number)*i + number, self.view.frame.size.width, self.view.frame.size.height/number);
    myButton.backgroundColor = [UIColor blackColor];
    [self.view addSubview:myButton];
    }


}
于 2012-07-23T08:12:17.960 回答
0

也许这可能有效?对不起,我已经很久没有使用self.view.frame过了,但你明白了。

- (void)viewDidLoad
{
    [super viewDidLoad];
    int number;

    for(int i=0 ; i<9 ; i++)
    {
        UIButton *myButton = [[UIButton alloc] init];
        myButton.frame = CGRectMake(i * self.view.frame.origin.x / number,
                                    self.view.frame.origin.y,
                                    self.view.frame.size.width,
                                    self.view.frame.size.height / number); //this "10" i want also dynamically
        myButton.backgroundColor = [UIColor blackColor];
        [self.view addSubview:myButton];
    }
}
于 2012-07-23T08:03:33.433 回答
0

您需要为正确显示定义按钮的大小,不幸的是,如果没有按钮的大小,您将无法实现您想要的,因为系统如何知道您想要显示的按钮大小......?

- (void)viewDidLoad
{
    [super viewDidLoad];

    Float32 _spaceBetweenButtons = 8.f;
    Float32 _offsetY = 32.f;
    Float32 _buttonWidth = 300.f; // width fo button
    Float32 _buttonHeight = 32.f; // height of the button

    for (int i = 0 ; i < 9 ; i++) {
        UIButton *_myButton = [[UIButton alloc] initWithFrame:CGRectMake(0.f, 0.f, _buttonWidth, _buttonHeight)];
        [_myButton setBackgroundColor:[UIColor blackColor]];
        [_myButton setTitle:[NSString stringWithFormat:@"button #%d", i] forState:UIControlStateNormal]; // just add some text as title
        [self.view addSubview:_myButton];
        [_mybutton setCenter:CGPointMake(self.view.frame.size.width / 2.f, _offsetY + i * (myButton.frame.size.height + _spaceBetweenButtons))];
    }
}

如果你想动态计算按钮的大小并且你想将按钮的高度与视图的高度对齐,这是一种方法:

NSInteger _numberOfButtons = 20;
Float32 _spaceBetweenButtons = 8.f;
Float32 _calculatedHeight = (self.view.frame.size.height - (_numberOfButtons + 1 * _spaceBetweenButtons)) / _numberOfButtons;

并且方法与上面相同,但我不确定在数百个按钮的情况下您是否会获得良好的 UI。:)

于 2012-07-23T08:47:59.733 回答