0

我想用网格创建带有 52 个正方形或按钮的视图(一年中的 52 周),但我不知道应该如何对齐它们或如何将它们放在框架中

(您将有 13 行和 4 列),但是如果您尝试使用此代码,它不是 algin :我不知道应该如何创建框架以将所有按钮放在框架的一侧。

这是我的代码:

- (void)viewDidLoad
{
[super viewDidLoad];
int rows = 13, columns = 4;

for (int y = 0; y < rows; y++) {
    for (int x = 0; x < columns; x++) {
        UIButton * button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        button.frame = CGRectMake(58 * x, 31 * y, 58, 31);

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

    }
}



}


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

3 回答 3

4

不要将按钮直接添加到控制器的视图中,而是创建一个包含所有按钮的子视图。然后,将此子视图居中。这是您可以使用的代码:

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

        [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];

如果您希望按钮占据整个视图,请调整按钮的宽度和高度(您使用了 58 和 31)。

于 2012-06-19T09:59:39.887 回答
1

你能用这个吗:

CGPoint center = CGPointMake([self.view bounds].size.width/2.0, [self.view bounds].size.height/2.0);    
[button setCenter:center];
于 2012-06-19T09:56:23.507 回答
0

将此代码写入AppDelegate.m文件中。只是检查一下。我运行这个程序,它在导航栏下方运行良好。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController_iPhone" bundle:nil] autorelease];
    } else {
        self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController_iPad" bundle:nil] autorelease];
    }
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:self.viewController];

    navigationController.navigationBar.barStyle = UIBarStyleDefault; 
    //navigationController.navigationBar.hidden = YES;
    //navigationController.navigationBar.frame = CGRectMake(0, 20, 320, 40);
   // self.window.rootViewController = self.viewController;
    [self.window addSubview:navigationController.view];
    [self.window makeKeyAndVisible];
    return YES;
}
于 2012-06-19T10:10:40.073 回答