【问题标题】:Changing constraints in objective-C在 Objective-C 中改变约束
【发布时间】:2019-08-08 14:48:12
【问题描述】:

我在viewDidLoad 中使用它设置了容器的顶部约束:

[[NSLayoutConstraint constraintWithItem:_container attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1 constant: 0.00]setActive:true];

但是我想在按钮出现时更改这些约束,这就是那个功能

-(void)didConnect{
    [[self connectToKestrelButton] setHidden:NO];
    [[self cancelButton] setHidden:YES];
    [[NSLayoutConstraint constraintWithItem:_container attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1 constant: 60.00]setActive:true];
}

但是当这个函数被调用时,约束更新

-(void)didDisconnect{
    [[self connectToKestrelButton] setHidden:YES];
    [[self cancelButton] setHidden:YES];
    [[NSLayoutConstraint constraintWithItem:_container attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1 constant: 0.00]setActive:true];
}

问题是调用该函数时容器顶部约束没有改变,出了什么问题?

【问题讨论】:

  • 您是否正在通过代码创建_container 和两个按钮?或者你有没有在 IB/Storyboard 中列出它们(并给予它们约束)?
  • 我在故事板中给了他们约束

标签: ios objective-c xcode constraints


【解决方案1】:

如果您在 Storyboard 中创建了 _container 并为其设置了约束,那么您的代码将添加 additional 约束(我希望您会收到警告/错误消息在调试控制台中)。

相反,从 Storyboard 创建到 _container 的顶部约束的 IBOutlet 连接,例如:

@property (strong, nonatomic) IBOutlet NSLayoutConstraint *containerTopConstraint;

然后,在viewDidLoad()

_containerTopConstraint.constant = 0.0;

而且,当你想改变它时,只需改变常数:

-(void)didConnect{
    [[self connectToKestrelButton] setHidden:NO];
    [[self cancelButton] setHidden:YES];
    _containerTopConstraint.constant = 60.0;
}

-(void)didDisconnect{
    [[self connectToKestrelButton] setHidden:YES];
    [[self cancelButton] setHidden:YES];
    _containerTopConstraint.constant = 0.0;
}

【讨论】:

    猜你喜欢
    • 2014-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-15
    相关资源
    最近更新 更多