我正在使用以下代码以编程方式创建视图:

      let statusfilterui = UIView(frame: CGRectMake(0, 300, 0, 0))
    var height : CGFloat = 0
    var width : CGFloat = 0
    self.cancelledByAdmin.frame = CGRectMake(0,0,0,0)
    if width == 0{
        width = self.cancelledByAdmin.frame.width
        height = self.cancelledByAdmin.frame.height
    }
    let cancelledByAdminlabel = UILabel(frame: CGRectMake(0, 0, 0, 0))
    cancelledByAdminlabel.text = "لغو شده توسط پذیرش"
    cancelledByAdminlabel.sizeToFit()
    self.cancelledByAdmin.frame = CGRectMake(cancelledByAdminlabel.frame.width+10, 0, 0, 0)
    let cancelledLabel = UILabel(frame: CGRectMake(0, height+10, 0, 0))
    cancelledLabel.text = "لغو شده توسط کاربر"
    cancelledLabel.sizeToFit()
    self.cancelled.frame = CGRectMake(cancelledLabel.frame.width+10, height + 10, 0, 0)
    let reservedLabel = UILabel(frame: CGRectMake(0, 2*(height + 10), 0, 0))
    reservedLabel.text = "لغو شده توسط پذیرش"
    reservedLabel.sizeToFit()
    self.reserved.frame = CGRectMake(reservedLabel.frame.width+10, 2*(height + 10), 0, 0)
    let deprecatedLabel = UILabel(frame: CGRectMake(0, 3*(height + 10), 0, 0))
    deprecatedLabel.text = "منقضی شده"
    deprecatedLabel.sizeToFit()
    self.deprecated.frame = CGRectMake(deprecatedLabel.frame.width+10, 3*(height + 10), 0, 0)
    statusfilterui.addSubview(self.cancelledByAdmin)
    statusfilterui.addSubview(cancelledByAdminlabel)
    statusfilterui.addSubview(self.cancelled)
    statusfilterui.addSubview(cancelledLabel)
    statusfilterui.addSubview(self.reserved)
    statusfilterui.addSubview(reservedLabel)
    statusfilterui.addSubview(self.deprecated)
    statusfilterui.addSubview(deprecatedLabel)
    print(statusfilterui.frame.width)
    statusfilterui.sizeToFit()
    print(statusfilterui.frame.width)
    self.filterview.addSubview(statusfilterui)
    print(statusfilterui.frame.width)

我想通过获取视图宽度来居中我的statusfilterui,但问题是我要打印statusfilterui.frame.width3次,每次在控制台中打印0.0。怎么了?

最佳答案

先将statusfilterui添加到父级。然后调用statusfilterui.sizeToFit()。这样就可以了。

parentView.addSubview(statusfilterui)
statusfilterui.sizeToFit()

Apple doc on sizeToFit()

10-08 05:46