大佬教程收集整理的这篇文章主要介绍了ios – 使用NSLayoutConstraint垂直居中两个视图,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我想根据这些要求在主视图中定位元素:
>两个元素应水平居中,即center.x坐标应全部相等(视图,图像和按钮);
>这两个元素应按以下方式垂直居中:分隔符(灵活) – imageview – 分隔符(固定,假设30分) – 按钮 – 分隔符(灵活).最上面和最下面的分隔符应该具有相同的大小(这是居中的含义).
到目前为止,我所做的一直是使用NSLayoutAttributeCenterX和NSLayoutRelationEqual将两个元素的X坐标居中到同一个视图属性.
根据我的想法,最后一部分是修复它们的垂直对齐.
我尝试使用@“V:| – [imageview(360)] – [button(70)] – |”但它不起作用(无法同时满足约束.).
如果我使用@“V:| – [imageview(360)] – [按钮] – |”我觉得一切都很好.也就是说,顶部是完美的但是按钮被拉伸以填充内部分隔符和视图底部之间的间隙.
如何使这些元素固定大小并让自动布局只是弄清楚如何将它们放在视图中?
NSnumber *sepHeight = @60.0F; // Center the two views horizontally [self.view addConsTraint:[NSLayoutConsTraint consTraintWithItem:imageView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]]; [self.view addConsTraint:[NSLayoutConsTraint consTraintWithItem:button attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]]; // Position the two views one below the other,using the separator height defined above [self.view addConsTraints:[NSLayoutConsTraint consTraintsWithVisualFormat:@"V:[imageview]-sepHeight-[button]" options:0 metrics:NSDictionaryOfVariableBindings(sepHeight) views:views]]; // Force the button distance from the bottom to be the half of the size of the content CGFloat constant = (imageview.frame.size.height + button.frame.size.height + [sepHeight FloatValue]) / 2.0; [self.view addConsTraint:[NSLayoutConsTraint consTraintWithItem:button attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1 constant:constant]];
棘手的部分是恒定值.该值是所有视图高度的一半,包括它们的分隔符.这意味着,如果imageview的高度为360,按钮的高度为70,分隔符为60,则该常量将为(360 70 60)/ 2 = 245.
确实应该有一种更聪明的方式,但是现在我觉得这没关系.
以上是大佬教程为你收集整理的ios – 使用NSLayoutConstraint垂直居中两个视图全部内容,希望文章能够帮你解决ios – 使用NSLayoutConstraint垂直居中两个视图所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。