2013-03-18 63 views
0

我想在UITableView的标题部分显示UIButton。这是我曾尝试设置按钮框架适合视图

UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0,0, 285, 44)]; 

    UIButton *headerViewButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
    headerViewButton.frame = CGRectMake(headerView.bounds.size.width * 7/5, headerView.bounds.size.height * 1/4, 320.0, 30.0); 
    headerViewButton.backgroundColor = [UIColor grayColor]; 
    [headerViewButton setTitle:@"Import main list from other field >" forState:UIControlStateNormal]; 
    [headerViewButton addTarget:self 
          action:@selector(buttonPressed:) 
       forControlEvents:UIControlEventTouchDown]; 

    [headerView addSubview:headerViewButton]; 

的问题是我有调节按钮框很难,所以,它在横向模式适合精细以及肖像模式的代码。我对使用Interface Builder不太舒服。如何正确调整按钮框架以适合视图。

我一直在使用setAutoresizingMask

UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0,0, 320, 44)]; 
UIButton *headerViewButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
    headerViewButton.frame = CGRectMake(headerView.bounds.size.width * 7/5, headerView.bounds.size.height * 1/4, 290, 30.0); 
    headerViewButton.backgroundColor = [UIColor grayColor]; 
    [headerViewButton setTitle:@"Import main list from other field >" forState:UIControlStateNormal]; 
    [headerViewButton addTarget:self 
         action:@selector(buttonPressed:) 
       forControlEvents:UIControlEventTouchDown]; 

    [headerViewButton setAutoresizingMask:UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleWidth]; 

    [headerView addSubview:headerViewButton]; 

由于应用程序加载的第一次,该按钮丢失试过,但我改变了方向,会出现按钮。每次尝试时,它都是一样的模式。应用程序第一次加载时,该按钮将丢失,并在此之后出现在两个方向上。

+0

作为rmaddy指出,你设置奇怪的按钮位置:'headerViewButton.frame = CGRectMake(headerView.bounds.size.width * 7/5,headerView.bounds.size.height * 1/4,290,30.0) ;'所以'x = headerview.width * 1.4 = 320 * 1.4'这是屏幕外 – 2013-03-19 20:35:00

回答

0

您需要将按钮的autoresizingMask设置为适当的值。这些值取决于按钮的大小和/或位置在其父视图大小更改时如何调整。

在您发布的代码中,使按钮比其父视图更宽是很奇怪的。

0

尝试设置

[headerViewButton setAutoresizingMask:UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth]; 

这种方式将调整为上海华改变。 (与在IB中设置自动调整选项相同)