3

我有这个代码,我想让我的按钮变成一个正方形,也在导航栏下,你能帮帮我吗

提前致谢!

我想让我的按钮变成一个正方形

- (void)viewDidLoad
{
[super viewDidLoad];



int rows = 13, columns = 4;
UIView *buttonView = [[UIView alloc] initWithFrame:CGRectMake(0.f, 0.f, 70*columns, 70*rows)];
for (int y = 0; y < rows; y++) {
    for (int x = 0; x < columns; x++) {
        UIButton * button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        button.frame = CGRectMake(70 * x, 28 * y, 70, 28);

        [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [buttonView addSubview: button];

    }
 }

// Center the view which contains your buttons
CGPoint centerPoint = buttonView.center;
centerPoint.x = self.view.center.x;
buttonView.center = centerPoint;
[self.view addSubview:buttonView];    

}


-(void)buttonPressed:(UIButton *)button
{
NSLog(@"button %u -- frame: %@", button.tag, NSStringFromCGRect(button.frame));
}

编辑 2

我使用边框时的错误

    [button.layer setBorderWidth:1.0]; 
    [button.layer setBorderColor:[UIColor blackColor]];

在此处输入图像描述

4

3 回答 3

1

定义一个整数变量并将其设置为按钮标题

int rows = 13, columns = 4;
int number=1;
UIView *buttonView = [[UIView alloc] initWithFrame:CGRectMake(0.f,44, 70*columns, 70*rows)];
for (int y = 0; y < rows; y++) {
    for (int x = 0; x < columns; x++) {
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(75 * x, 75 * y, 70, 70);
        button.backgroundColor=[UIColor redColor];
        [button setTitle:[NSString stringWithFormat:@"%d",number] forState:UIControlStateNormal];

        button.tag=number;
        [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [buttonView addSubview: button];
        number++;
    }
}

希望这将帮助您移动到下一个屏幕。Button.tag 给出了您选择的确切按钮。

于 2012-06-20T05:22:11.213 回答
0

尝试这个

int rows = 13, columns = 4;  
UIView *buttonView = [[UIView alloc] initWithFrame:CGRectMake(0.f,44, 70*columns, 70*rows)];
for (int y = 0; y < rows; y++) {
    for (int x = 0; x < columns; x++) {
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(75 * x, 75 * y, 70, 70);
        button.backgroundColor=[UIColor redColor];
        [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [buttonView addSubview: button];

    }
}

// Center the view which contains your buttons
CGPoint centerPoint = buttonView.center;
centerPoint.x = self.view.center.x;
buttonView.center = centerPoint;
[self.view addSubview:buttonView]; 

要使用图层属性,您需要在项目中添加 QuartzCore.framework。

于 2012-06-19T15:28:43.630 回答
0

您正在设置大小为 70x28 的按钮,因此如果您想要一个 70x70 的按钮,则必须更改 button.frame = CGRectMake(70*x, 70*y, 70, 70),这样您将拥有方形按钮。

另外,你确定这是一个导航栏还是一个工具栏?如果您使用使用导航栏的 NavigationController,Apple 自己的 SDK 将不允许您轻松绘制它。

无论如何,在您的情况下,只需从 y = 44 开始绘制按钮,您就不会让按钮与工具栏重叠。

于 2012-06-19T14:46:04.340 回答