【问题标题】:setFrame does not work when I add UIKit elements to a subview当我将 UIKit 元素添加到子视图时,setFrame 不起作用
【发布时间】:2024-01-05 23:45:01
【问题描述】:

我有如下视图:

当我尝试在 CGSizeZero 框架中折叠 schedinaContView 时,它仅在 schedina 的子视图为空时才有效。

这是我的代码:

-(void)prepareFloatSchedina
{
    schedinaVC = [[SchedinaViewController alloc] initWithNibName:@"SchedinaViewController" bundle:nil];
    schedinaVC.view.frame = self.schedina.frame;
    [self.schedina addSubview: schedinaVC.view];

    schedinaExpandedSize = _schedinaContView.frame.size;
    CGRect frame = [UIUtilCollection frameInSuperFrame:self.view.frame atCornerWithSize:schedinaCompressedSize];
    _schedinaContView.frame = frame;

    NSLog(NSStringFromCGRect(_schedinaContView.frame));

    UIButton *bottone = [[UIButton alloc] initWithFrame:CGRectMake(0.0, 0.0, 20.0, 20.0)];
    [bottone setTitle:@"Ciao" forState:UIControlStateNormal];
    [self.schedina addSubview:bottone];
}

这是 NSLog 的结果:

{{1004, 748}, {0, 0}}

但是 _schedinaContView 仍然存在于视图中!

所以,如果我删除 UIButton,它会完美运行。这就是为什么?

已解决:

我解决了将方法[translatesAutoresizingMaskIntoConstraints:] 的参数设置为YES 然后我在焦点视图上停用了 NSLayoutConstraint,并在我尝试打开视图时重新激活。

[_schedinaContView setTranslatesAutoresizingMaskIntoConstraints:YES];
_verticalSpace.active = NO;

【问题讨论】:

    标签: ios objective-c autolayout frame


    【解决方案1】:

    我看到了自动布局约束。 setFrame 不适用于自动布局。 改用约束setFrame 或关闭自动布局。

    【讨论】:

    • 是的,我使用它。我也尝试在 setFrame 之后使用 [updateConstraints],但它不起作用。
    • @LucaD,如果你使用自动布局,你根本不需要setFrame。另外最好将translatesAutoresizingMaskIntoConstraints 设置为NO 以避免自动布局冲突。
    • 好的,但是阅读有关 AutoLayout 的文档我阅读了有关该方法的参数 = YES。不过,我想我解决了,我会在下一个答案中解释
    最近更新 更多