【问题标题】:Adding multiple UIButtons to an UIView将多个 UIButtons 添加到 UIView
【发布时间】:2010-11-06 17:21:24
【问题描述】:

我以编程方式向 UIView(通过 addSubview)添加了一些按钮。但是,它们显示为叠加层(因此我总是只看到最后一个按钮)。如何在现有按钮下方添加新按钮?

问候

【问题讨论】:

  • 您能否通过说明当您说“下方”时所指的轴来澄清问题?
  • 是的,我指的是 y 轴。

标签: iphone cocoa-touch uiview uibutton


【解决方案1】:

你可以像这样偏移按钮

int newX = previousButton.frame.origin.x + previousButton.frame.size.width ;
int newY = previousButton.frame.origin.y ;

并在创建新按钮时为其设置框架:

[[UIButton alloc] initWithFrame:CGRectMake(newX,newY,100,100)];

或稍后设置框架

newButton.frame = CGRectMake(newX,newY,100,100);

【讨论】:

  • 真是巧合,我同时做了一个类似的解决方案 ;-) 这是我的:roundedButton.frame = CGRectMake(previousFrame.origin.x + previousFrame.size.width + 5, 0, 200,30);谢谢!
【解决方案2】:

设置 UIView 的框架原点以将 UIButtons 布局在您希望的位置:

CGRect buttonFrame = button.frame;
buttonFrame.origin = CGPointMake(100.0f, 100.0f);
button.frame = buttonFrame;
view.addSubview(button);

【讨论】:

  • 您需要添加“button.frame = buttonFrame;”在第 2 行或第 3 行之后完成这项工作。否则,您只是在修改框架矩形的副本。
【解决方案3】:

您可以使用视图的 insertSubview:atIndex 方法或 insertSubview:belowSubview。

UIButton *myButton = [[UIButton alloc] initWithFrame:CGRectMake(0,0,100,100)];

[myView insertSubview:myButton belowSubview:previousButton];

[myView insertSubview:myButton atIndex:0];

【讨论】:

  • 我不确定 Stefan 指的是 Y 轴还是 Z 轴 - 但我们之间已经涵盖了两者。
  • 也想不通,但就像你说的,我们两个都搞定了。
【解决方案4】:

谢谢你们的回答。

我做了(水平)与此代码对齐:

if([myContainer.subviews lastObject] == nil){
        NSLog(@"NIL");
        [myContainer insertSubview:roundedButton atIndex:0];
    }else{
        [myContainer insertSubview:roundedButton belowSubview:[tagsContainer.subviews lastObject]];
    }

它在技术上有效,但仍然覆盖按钮。我必须找到一种方法,如何不覆盖它们......

【讨论】:

  • 覆盖按钮是什么意思?
  • 它们在视觉上显示为一个按钮,因为它们仍然在同一位置(0.0、0.0)。所以,我的目标是从前一个 UIButton ([myContainer.subviews lastObject]) 中获取新的起始位置。我认为这与 UIButtons 框架有关。但我不知道,如何获得职位。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
  • 2014-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多