我正在制作一个插槽 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
}
但是,在 Storyboard 上添加 AutoLayout 会使 ipad 上的 View 变宽,这很好。但插槽不居中。
我很感激任何带有代码或自动布局的解决方案,谢谢
最佳答案
每个 subview 更改的第二个 Align Center X Multiplier
第一乘数应为 0.25,第二应为 0.75,第三应为 1.25,第四应为 1.75
关于ios - 将 uiviews 在其 parentView 中正确居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53486696/