如何在导航栏下的iOS中绘制Square按钮

时间:2012-06-19 14:41:21

标签: objective-c ios xcode

我有这个代码,我希望我的按钮为方形,并且导航栏下方还有 ,你会帮我吗

提前致谢!

我希望将按钮设为正方形

- (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

我使用border

时的错误
    [button.layer setBorderWidth:1.0]; 
    [button.layer setBorderColor:[UIColor blackColor]];

enter image description here

3 个答案:

答案 0 :(得分:0)

你正在设置尺寸为70x28的按钮,所以如果你想要一个按钮70x70,你必须改变button.frame = CGRectMake(70 * x,70 * y,70,70),这样你就会有方形按钮

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

在任何情况下,只需从y = 44开始绘制按钮,就不会有按钮与工具栏重叠。

答案 1 :(得分: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。

答案 2 :(得分:0)

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

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提供您选择的确切按钮。