【发布时间】:2017-06-10 15:25:34
【问题描述】:
我知道如何以编程方式将 UIButton 添加到 UIView。但是在之前的 YPosition 中添加了一定数量的 UIButtons 之后,我一直坚持在新的 YPosition 中添加 UIButton。
这是我的情况:
要添加的 UIButton 数量来自 NSArray - 我们取 20
UIView 已经添加到 UIViewController - 让我们调用
'按钮视图'我正在使用循环创建 UIButton(最多 20 个)。我已经设置了
buttonWidth 为 70,buttonHeight 为 45我正在获取屏幕尺寸并将其除以 buttonWith,所以
至于计算每行可以容纳的项目数 或每个 Y 位置。如果屏幕宽度为 414,则 414/70 = ~5.9,我将其视为
前 5 个 UIButton 的 YPosition 为 0,XPosition 从 0 开始,为后续按钮添加 buttonWidth。
接下来的 5 个 UIButton (6-10) 应该将新的 YPosition 设置为 1-5 UIButton Yposition(0)+buttonHeight(45)+somespace(10)= 55 并且 XPostion 应该 从 0 开始。
对于下一组 UIButtons(11-15),YPosition 应该是
Yposition(55)+buttonHeight(45)+somespace(10)= 100 和 XPosition 以 0 开头
如何做到这一点?下面是我的代码
xPos = 8.0f;
yPos = 0.0f;
totalSlots =timeslots.Count - //Total Number UIButtons to be creted
buttonWidth = 70;
buttonHeight = 45;
buttonViewWidth = this.view.frame.size.width // I'm getting the screen
buttonPerLine = scrollViewWidth / (buttonWidth + 10); // This calculates no.of.buttons per line/Y Position. I'm rounding off as said before
numberOfLine = totalSlots / buttonPerLine // This gives how many lines needed
for (int i = 0; i < totalSlots; i++)
{
timeSlotbtn[i] = new UIButton();
timeSlotbtn[i] = new UIButton();
timeSlotbtn[i].Frame = new CGRect(xPos, yPos, buttonWidth, buttonHeight);
timeSlotbtn[i].SetTitle(buttonText, UIControlState.Normal);
timeSlotbtn[i].Layer.BorderWidth = 2.0f;
timeSlotbtn[i].Layer.CornerRadius = 3;
timeSlotbtn[i].Tag = i;
timeSlotbtn[i].TitleLabel.Font = UIFont.FromName("HelveticaNeue-bold", 14.0f);
xPos = timeSlotbtn[i].Frame.Location.X + buttonWidth + buttonSpace;
timeslotScrollView.AddSubview(timeSlotbtn[i]);
}
请注意,上面的代码是用 Xamarin.iOS 编写的。如果您知道解决方案,那么您可能可以用 Objective-c 编写。总之,逻辑应该是一样的。
【问题讨论】:
-
我解决了这个问题。如果有人正在寻找相同的代码,我已经更新了代码。
标签: objective-c uiview xamarin.ios uibutton