ios - 将 uiviews 在其 parentView 中正确居中

标签 ios swift

我正在制作一个插槽 UIView()。我对 UIView() 进行了子类化,一切正常。

现在我也在尝试使用自动布局来支持 ipad。

这是我想要的:

img1

我的成就:

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 变宽,这很好。但插槽不居中。

这是我在 iPad 上的调试层次结构: s

我很感激任何带有代码或自动布局的解决方案,谢谢

最佳答案

首先为每个 subview 设置约束 enter image description here

每个 subview 更改的第二个 Align Center X Multiplier

enter image description here

第一乘数应为 0.25,第二应为 0.75,第三应为 1.25,第四应为 1.75

关于ios - 将 uiviews 在其 parentView 中正确居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53486696/

相关文章:

ios - 是否可以为每台设备设置一个布局而不是自动布局?

ios - 在 iOS swift 中单击文本字段之前,文本不可见

ios - 从另一个 ViewController 访问变量

ios - 侧边菜单和桌面 View 自定义

ios - 当手指经过时,Swift Button 的作用就像一个传感器

ios - Swift didReceiveRemoteNotification - 无论应用用户位于何处,都导航到 rootviewcontroller(现在有错误消息)

ios - 在自定义 UITableViewCell 中设置元素的角半径

ios - Xcode I Tableview viewItemWithTag 无法从 UITableViewCell 转换为 UIImageView

ios - 无法导入 Alamofire

ios - 如何更改 iOS 中 JTCalenderView 的工作日顺序?