【问题标题】:Set the button frame fit to the view将按钮框架设置为适合视图
【发布时间】:2013-03-18 16:19:53
【问题描述】:

我想在 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];

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

【问题讨论】:

  • 正如 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 在屏幕外

标签: ios ipad uibutton bounds


【解决方案1】:

您需要将按钮的autoresizingMask 设置为适当的值。这些值取决于您希望按钮的大小和/或位置随着其父视图大小的变化而调整的方式。

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

【讨论】:

    【解决方案2】:

    尝试设置

    [headerViewButton setAutoresizingMask:UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth];
    

    这样它会随着超级视图的变化而调整大小。 (与在 IB 中设置自动调整大小选项相同)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多