iCarousel 自动布局乘数问题
Posted
技术标签:
【中文标题】iCarousel 自动布局乘数问题【英文标题】:iCarousel AutoLayout Multiplier issue 【发布时间】:2016-06-11 10:59:43 【问题描述】:我正在尝试在 iCarousel 布局上使用乘数,但它们似乎根本没有任何影响。这是我的代码:
_carousel = [[iCarousel alloc]init ];
self.items = [NSMutableArray array];
for (int i = 0; i < 10; i++)
[_items addObject:@(i)];
_carousel.type = iCarouselTypeCylinder;
_carousel.delegate = self;
_carousel.dataSource = self;
_carousel.translatesAutoresizingMaskIntoConstraints = false;
[self.view addSubview:_carousel];
[_carousel.centerXAnchor constraintEqualToAnchor:self.view.layoutMarginsGuide.centerXAnchor].active = true;
[_carousel.bottomAnchor constraintEqualToAnchor:self.view.layoutMarginsGuide.bottomAnchor constant:-80].active = true;
[_carousel.widthAnchor constraintEqualToAnchor:self.view.widthAnchor multiplier:40.0/100.0].active = true;
[_carousel.heightAnchor constraintEqualToAnchor:self.view.heightAnchor multiplier:30.0/100.0].active = true;
我还注意到,如果输入一个常量值,比如 -20 in:
[_carousel.bottomAnchor constraintEqualToAnchor:self.view.layoutMarginsGuide.bottomAnchor constant:-20].active = true;
iCarousel 远低于视图底部锚点,我不知道为什么?
任何人都可以回答这些问题,如果我忽略了任何事情,因为我是程序化布局的新手,请原谅我。
【问题讨论】:
【参考方案1】:您应该覆盖并将您的代码移动到loadView
以避免让自动布局引擎生成原型约束。例如:
- (void) loadView
[super loadView];
_carousel = [[iCarousel alloc]init ];
self.items = [NSMutableArray array];
for (int i = 0; i < 10; i++)
[_items addObject:@(i)];
_carousel.type = iCarouselTypeCylinder;
_carousel.delegate = self;
_carousel.dataSource = self;
_carousel.translatesAutoresizingMaskIntoConstraints = false;
[self.view addSubview:_carousel];
[_carousel.centerXAnchor constraintEqualToAnchor:self.view.layoutMarginsGuide.centerXAnchor].active = true;
[_carousel.bottomAnchor constraintEqualToAnchor:self.view.layoutMarginsGuide.bottomAnchor constant:-80].active = true;
[_carousel.widthAnchor constraintEqualToAnchor:self.view.widthAnchor multiplier:40.0/100.0].active = true;
[_carousel.heightAnchor constraintEqualToAnchor:self.view.heightAnchor multiplier:30.0/100.0].active = true;
一般来说,loadView
是您希望以编程方式将子视图添加到 UIViewController
子类的位置。
【讨论】:
谢谢你:)你能帮我解决这个问题吗? 你试过这个代码吗?这为我在运行代码时修复了自动布局问题,作为导致自动布局约束中断的原型约束。我在您的UIViewController
或UIView
生命周期中发布的代码在哪里?
我没有使用 IB,所以没有原型设计限制。这些代码块(constraintEqualToAnchor:乘法器方法)在程序的其他地方正常工作,但在 iCarousel 上却不行。我无法将此代码放在“loadView”中,因为在我的程序中,iCarousel 的设置发生在视图加载后并基于条件。 iCarousel 由 centerX 和底部锚点定位,但乘数没有效果,导致 iCarousel 在所有设备上的点数相同,这是我不想要的。我希望它在不同的屏幕尺寸上相应地调整大小
好的,所以这很奇怪...我已经注释掉了分配给 iCarousel 的每个约束,而是通过“initWithFrame”为其指定大小/位置,但我得到“无法同时满足约束” ' 警告??没有分配给它的约束?
您没有任何情节提要或 Xib 文件?您可以在loadView
中添加轮播,将其隐藏,如果不需要,稍后将其删除。自动布局为您生成约束。如果您在生成约束之前设置它们,它们将不会并且会给您预期的结果。以上是关于iCarousel 自动布局乘数问题的主要内容,如果未能解决你的问题,请参考以下文章