Ios 如何使用autolayout防止任意数量的动态创建的UIView重叠
如果事先没有定义UIView的数量,如何防止多个UIView重叠?我真的不在乎它们在屏幕上的位置,只要满足特定的填充定义 使用autolayout似乎是一种方法,但我无法正确使用它 我可能需要一个循环Ios 如何使用autolayout防止任意数量的动态创建的UIView重叠,ios,objective-c,uiview,autolayout,Ios,Objective C,Uiview,Autolayout,如果事先没有定义UIView的数量,如何防止多个UIView重叠?我真的不在乎它们在屏幕上的位置,只要满足特定的填充定义 使用autolayout似乎是一种方法,但我无法正确使用它 我可能需要一个循环 UIView *prevView = nil; for (UIView *aView in [self subViews]) { // would really need to check foreach subview if this view isn't overlapping //
UIView *prevView = nil;
for (UIView *aView in [self subViews])
{
// would really need to check foreach subview if this view isn't overlapping
// lets assume just 2 views for simplicity
if (CGRectIntersectsRect(aView.frame,prevView.frame))
{
// update the view frame
// or update autolayout constraints
}
}
// might need to call the function recursively if first pass wasn't successful
根据您的具体需求,您可以:
while(CGRectIntersectsRect(aView.frame, prevView.frame)){
// Re-locate aView
[aView setCenter: CGPointMake(arc4random_uniform(self.view.frame.size.width), arc4random_uniform(self.view.frame.size.height))];
}
缺点当然是性能:由于有很多子视图,可能需要一段时间(以及许多随机生成的数字)才能找到可用空间。
如果你使用它,你至少应该确保你的应用不会陷入无限循环中根据您的具体需求,您可以:
while(CGRectIntersectsRect(aView.frame, prevView.frame)){
// Re-locate aView
[aView setCenter: CGPointMake(arc4random_uniform(self.view.frame.size.width), arc4random_uniform(self.view.frame.size.height))];
}
缺点当然是性能:由于有很多子视图,可能需要一段时间(以及许多随机生成的数字)才能找到可用空间。
如果你使用它,你至少应该确保你的应用不会陷入无限循环中