gpt4 book ai didi

iphone - 如何在带有对齐中心的uiview中并排放置按钮

转载 作者:行者123 更新时间:2023-11-29 11:01:32 25 4
gpt4 key购买 nike

我有一个 uiview,我必须以编程方式在 uiview 的中心并排放置几个按钮,如图所示

类似这个图,按钮应该放在uiview的中心

 --------------------------------
| ---- ---- ---- |
|| | | | | | |
|| 1B | | 3B | | 5B | |
| ---- ---- ---- |
| ---- ---- |
|| 2B | | | |
|| | | 4B | |
| ---- ---- |
--------------------------------

最佳答案

这是我已经解决的问题。 Source Code

一个枚举类型,表示你想要垂直或水平排列的项目

typedef enum {
ArrangementTypeHorz = 1,
ArrangementTypeVert = 2
}ArrangementType;

声明数字或行列和排列类型

@interface ATTViewController ()

{
ArrangementType _arrangementType;

NSUInteger _rows;
NSUInteger _columns;

}

@end

方法计算 item index wrt superView 的框架

- (CGRect)frameForItemAtIndex:(NSUInteger)index inSuperView:(UIView *)superView
{
CGFloat blockWidth = floorf(superView.frame.size.width/_columns);
CGFloat blockHeight = floorf(superView.frame.size.height/_rows);

NSUInteger row = 0;
NSUInteger column = 0;

if (_arrangementType == ArrangementTypeHorz) {
row = floorf((CGFloat)index/_columns);
column = index - row*_columns;
}else{
column = floorf((CGFloat)index/_rows);
row = index - column*_rows;
}

CGFloat xOffset = 5.0f;
CGFloat yOffset = 5.0f;

return CGRectMake(blockWidth*column+xOffset,
blockHeight*row+yOffset,
blockWidth-(2*xOffset),
blockHeight-(2*yOffset));
}

将按钮添加到 containerView。添加时设置行、列和排列类型

- (void)addButtonsToContainerView
{
NSUInteger numberOfItems = 5;

_rows = 2;
_columns = 3;

_arrangementType = ArrangementTypeVert;

NSUInteger itemCount = 0;

while (itemCount<numberOfItems)
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
CGRect frame = [self frameForItemAtIndex:itemCount inSuperView:self.containerView];
[button setFrame:frame];
NSString *title = [NSString stringWithFormat:@"Button %d",itemCount+1];
[button setTitle:title forState:UIControlStateNormal];

[self.containerView addSubview:button];

itemCount ++;
}
}

关于iphone - 如何在带有对齐中心的uiview中并排放置按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15698327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com