[英]Properly center uiviews inside their parentView
我正在制作一个插槽UIView()
。 我有子类化UIView()
,一切都很好。
现在,我也尝试使用自动版式来支持iPad。
这就是我想要的:
我所取得的成就:
public protocol GDTextSlotDelegate: class{
func onTextEntered(_ finalText: String)
}
@IBDesignable
final public class GDTextSlot: UIView, UIKeyInput {
public weak var delegate: GDTextSlotDelegate? = nil
/ ... /
}
@IBInspectable
public var numberOfSlots: Int = 4 {
didSet{
/ .. /
}
}
@IBInspectable
public var baseWidth: CGFloat = 30.0 {
didSet{
/ .. /
}
}
同时生成一个新的广告位:
/// Calculate X position of slot and make sure
/// the whole group is always in center of the view
private func calcX() -> CGFloat{
return ((frame.width - (baseWidth * CGFloat(numberOfSlots))) / 2) + (CGFloat((currentSlot - 1)) * CGFloat(baseWidth))
}
private func calcFrame() -> CGRect{
return CGRect(x: calcX(), y: 0, width: baseWidth, height: frame.height)
}
/// Initiate a new label for the slot!
private var label: UILabel{
let lbl: UILabel = UILabel()
lbl.frame = calcFrame()
lbl.text = "_"
lbl.textColor = UIColor.white
lbl.font = UIFont.boldSystemFont(ofSize: 25)
lbl.textAlignment = .center
lbl.tag = currentSlot
return lbl
}
最后一步:
public func generateSlots(){
for index in 1...numberOfSlots{
currentSlot = index
addSubview(label)
}
currentSlot = 1
}
但是,在情节提要板上添加AutoLayout可以使iPad上的视图变宽,这很好。 但插槽不会居中。
感谢使用代码或自动布局的任何解决方案,谢谢
当您像这样任意数目地对等地排列对象时,请使用UIStackView。 此屏幕快照显示了一个示例:
堆栈视图是具有中心对齐和均等填充的水平堆栈视图。 堆栈视图具有一个在其父视图中水平居中的约束(以及任意高度约束和顶部约束,对于此示例均不相关)。 这将导致其排列的子视图(插槽视图)的间距和大小均等,并且整个对象都集中在堆栈视图的超级视图中。
让我们分析一下我们如何获得特定的结果。
插槽视图的高度由其高度限制确定。
插槽视图之间的间隔由堆栈视图的间隔设置确定。
因此,唯一需要指定的就是插槽视图的宽度。 由堆栈视图本身的宽度约束设置。 知道插槽视图的所需宽度后,只需将该宽度乘以插槽视图的数量,将堆栈视图的间距乘以小于插槽视图的数量的一倍,将这两个视图加在一起,然后将堆栈视图的宽度约束设置为那。
因此,无论超级视图的大小如何,插槽视图最终看起来都完全相同,并且在其超级视图中水平居中。 真正很酷的部分是,我们可以增加或减少插槽视图的数量,并且它们都可以继续完美地工作,因为堆栈视图完成了排列它们的所有工作。
@canister_exister为情节提要方法提供了一个很好的解决方案。 用代码完成它也非常简单。 在您的情况下,请使用UIStackView
:
public func generateSlots(){
//Stack View
var stackView = UIStackView()
stackView.axis = UILayoutConstraintAxis.horizontal
stackView.distribution = UIStackViewDistributionEqualSpacing
stackView.alignment = UIStackViewAlignmentCenter
stackView.spacing = //spacing between each label
for index in 1...numberOfSlots{
currentSlot = index
var slotLabel = UILabel()
//customize your label here: don't need x and y
//these are width and height constraints for each label
view3.heightAnchor.constraint(equalToConstant: 20).isActive = true
view3.widthAnchor.constraint(equalToConstant: baseHeight).isActive = true
stackView.addArrangedSubview(label)
}
currentSlot = 1
stackView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(stackView)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.