我在UICollectionView
中使用了一个标头(补充视图)。在页眉上,我有一个标签,它离左边有一定的距离。我正在计算并设置约束的常数。一切都按预期进行。
如果现在更改了方向,则标签具有旧位置。现在,我需要更新所有标头的约束。调用invalidateLayout
不会更新约束。如何手动触发重新计算?
编辑:
这就是我的layoutSubviews
的样子,在这里进行重新计算:
public override void LayoutSubviews ()
{
this.width = this.collectionViewSize.Width;
this.itemWidth = (nfloat)Math.Round(this.width / numberOfItemsInRow);
leftSpacing.Constant = this.itemWidth * this.referencePoint;
if (leftSpacing.Constant == 0)
leftSpacing.Constant = SectionHeader.MIN_SPACING;
base.LayoutSubviews ();
}
正如你所看到的,这不是Objective-C,但你应该能够看到我在做什么。我取集合视图的宽度(在补充视图的实例化时设置),然后计算几乎与单元格实际大小对应的单元格宽度。使用referencePoint我确定位置。在这里你可以看到我的限制设置:
public SectionHeader (CGRect frame) : base (frame)
{
this.width = frame.Size.Width;
this.itemWidth = (nfloat)Math.Round(width / numberOfItemsInRow);
label = new UILabel (){
BackgroundColor = UIColor.White,
TextAlignment = UITextAlignment.Left
};
label.TranslatesAutoresizingMaskIntoConstraints = false;
AddSubview (label);
NSMutableDictionary viewsDictionary = new NSMutableDictionary();
viewsDictionary["label"] = label;
this.AddConstraints(NSLayoutConstraint.FromVisualFormat("V:|[label]|",(NSLayoutFormatOptions)0,null,viewsDictionary));
leftSpacing = NSLayoutConstraint.Create(label, NSLayoutAttribute.Left, NSLayoutRelation.Equal, this, NSLayoutAttribute.Left, 1, SectionHeader.MIN_SPACING);
leftSpacing.Priority = 250;
this.AddConstraint(leftSpacing);
this.AddConstraint(NSLayoutConstraint.Create(label, NSLayoutAttribute.Right, NSLayoutRelation.Equal, this, NSLayoutAttribute.Right, 1, 0));
}
在该代码中,与左侧距离的计算几乎相同,只是帧具有集合headerReferenceSize
的高度。宽度应该可以进行初始化。我使用标签的全高,我设置了引导空间,并将其固定在右侧。
您需要在视图控制器的主视图上调用layoutIfNeeded
,以便更新约束。像这样的东西应该起作用:
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
// Update the constraints here for the new orientation - toOrientation
// ...
[UIView animateWithDuration:duration animations: ^{
[self.view layoutIfNeeded];
}];
}
这将在方向更改时为布局更改设置动画。
您可以在layoutIfNeeded
调用之后添加一个断点,以查看帧是否符合预期。
如果约束不在视图控制器中,而是在UIView
子类中,则可以执行以下操作:
- (void)awakeFromNib {
[super awakeFromNib];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateIntrinsicConstraints) name:UIDeviceOrientationDidChangeNotification object:nil];
}
- (void)updateIntrinsicConstraints {
// Update your constraints here
[self.constraint setConstant:newValue];
// You might need to call [self layoutIfNeeded] here, if you don't call it in another place
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
如果这对你有用,请告诉我!
更新
您不应该手动更改SectionHeader的框架。您应该通过实现协议方法来做到这一点:
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section;
在将约束添加到标签后,可以在SectionHeader
的init方法中调用layoutIfNeeded
,然后添加断点以查看帧是否正确。
如果对你有用,请告诉我!