ios - 如何使用自动布局制作均匀间隔的图像行?

标签 ios swift autolayout

我刚刚开始在 Swift 中开发这款纸牌游戏,我试图弄清楚如何在屏幕顶部附近水平放置一排 6 张纸牌。

我尝试将 6 个 imageView 放入堆栈中,但我的手动约束最终导致最后一个图像拉伸(stretch)到边缘:

有人可以告诉我如何设置一行 imageView,使每个 imageView 都有固定的宽度并且都居中吗?我对自动布局有点陌生,所以屏幕截图会很有帮助。

最佳答案

我建议使用 UIStackView。看看下面的 Ray Wenderlich 教程:

https://www.raywenderlich.com/114552/uistackview-tutorial-introducing-stack-views

但是,在转向更复杂的 View (例如前面提到的堆栈 View )之前;您应该学习使用自动布局以避免犯任何愚蠢的错误。

这是来自同一站点的另一个很棒的教程:

https://www.raywenderlich.com/115440/auto-layout-tutorial-in-ios-9-part-1-getting-started-2

编辑:

改进的答案:

UIStackView 允许您轻松地将元素排列在行或列中。这可以为您节省大量时间,并使您的 Storyboard看起来更干净一些,因为需要的约束更少。

developer.apple.com上UIStackView的描述:

The UIStackView class provides a streamlined interface for laying out a collection of views in either a column or a row. Stack views let you leverage the power of Auto Layout, creating user interfaces that can dynamically adapt to the device’s orientation, screen size, and any changes in the available space. The stack view manages the layout of all the views in its arrangedSubviews property. These views are arranged along the stack view’s axis, based on their order in the arrangedSubviews array. The exact layout varies depending on the stack view’s axis, distribution, alignment, spacing, and other properties.

UIStackViews 功能并不止于简化的 View 对齐。事实上,您还可以更改定义堆栈 View 的属性。

The axis property determines the stack’s orientation, either vertically or horizontally.

The distribution property determines the layout of the arranged views along the stack’s axis.

The alignment property determines the layout of the arranged views perpendicular to the stack’s axis.

The spacing property determines the minimum spacing between arranged views.

The baselineRelativeArrangement property determines whether the vertical spacing between views is measured from the baselines.

The layoutMarginsRelativeArrangement property determines whether the stack view lays out its arranged views relative to its layout margins.

尽管有上述优点,UIStackView 也有局限性。

The UIStackView is a nonrendering subclass of UIView; that is, it does not provide any user interface of its own. Instead, it just manages the position and size of its arranged views. As a result, some properties (like backgroundColor) have no effect on the stack view. Similarly, you cannot override layerClass, drawRect:, or drawLayer:inContext:.

请注意,UIStackView 无法滚动。如果您需要滚动,请在 UIScrollView 中嵌入堆栈 View 。

希望这有帮助!

关于ios - 如何使用自动布局制作均匀间隔的图像行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37738240/

相关文章:

ios - Swift prepareForSegue 取消

ios - 在 Xcode 5 中向 super View 添加间距约束

ios - 如何为 ios 实现网格布局

ios - Swift 中的间歇性 fatal error (在展开可选值时意外发现 nil)

iphone - indexOfObject第一次返回0而不是NSNotFound

ios - 在 IB 中编辑 Tableview 并失去连接

swift - 在 XCode 8 中,我可以在哪里设置 View Controller 的 Storyboard ID?

swift - 如何在 Swift 4 中安全地解包字典值?

cocoa - NSImageView:水平适合容器宽度,垂直纵横比

ios - 当使用 .isActive = true 激活时,NSLayoutConstraint 对象位于何处?