2013-03-18 59 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中設置自動調整選項相同)