1

我试图通过 removeFromSuperview 删除约束来使 UILabel 增长。文本字段 1 被删除。但它仍然没有让 UILabel 变宽。我已在此处附上示例代码以供参考。它完全在故事板上。

这是我的 ViewDidLoad 方法:

  self.label1.text = @"label 1";
  self.label2.text = @"label 2";
  self.textfield1.text = @"text field 1";
  self.textfield2.text = @"text field 2";
  [self.textfield1 removeFromSuperview]; 

我不想拥有约束的 IBOutlet 并在代码上更新它。我试图把它放在故事板上一次。

4

2 回答 2

1

我认为您的标签 2 取决于其在文本字段 1 中的位置,并且您希望标签 2 在删除文本字段 1 时增长以占据文本字段 1 的空间。但是,由于标签 2 是(例如,文本字段右侧 20 像素1),当您删除文本字段 1 时,该约束被删除(它现在无效,因为文本字段 1 不再存在!)并且相对于超级视图生成一个默认约束。

有一个简单的解决方案,但它相当不完善 - 不是从超级视图中删除,而是将文本字段 1 的宽度设置为 0。然后您将看到标签 2 的位置发生了变化。

但是,为了获得更多控制权,我认为您仍然必须IBOutlet受到约束。

于 2015-05-29T19:00:46.757 回答
1

With the following technique, instead of removing the textfield, you can just set its text to nil. Its intrinsic content size will then have zero width, and your label will expand to fill the additional space.

  • Constrain both the label and textfield to their superview's nearest edge (i.e. 1 constraint each), and constrain their vertical position as you wish.
  • Add a horizontal space constraint between the label and textfield (e.g. with a constant gap of 8 points).
  • Increment the textfield's compression resistance priority, and its content hugging priority (both horizontal).

Im assuming your layout looks something like this:

|[label][textField]|

于 2015-05-29T20:16:08.523 回答