ios - 正在显示 View 但打印宽度显示为 0

标签 ios swift layout

我正在使用这段代码以编程方式创建我的 View :

      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)

我想通过获取 View 宽度使我的 statusfilterui 居中,但问题是我正在打印 statusfilterui.f​​rame.width 3 次并且每次在控制台中打印 0.0。怎么了?

最佳答案

首先将 statusfilterui 添加到父级。然后调用 statusfilterui.sizeToFit()。然后它应该可以工作。

parentView.addSubview(statusfilterui)
statusfilterui.sizeToFit()

Apple doc on sizeToFit()

关于ios - 正在显示 View 但打印宽度显示为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39306597/

相关文章:

ios - UICollectionView 不会居中

css - 如何删除 slider 和导航之间的空白区域?

layout - 使用 <DIV> 标签实现 3 列网站的最佳方式?

ios - 按顺序执行 swift nsurlsession 任务

ios - 如何在UIButton里面获取阴影

swift - 如何通过单击标签来制作进度条效果

swift - didSelect 只为同一个 pin 触发一次

html - 如何让表格扩展到整个页面

iphone - iOS初始化UIWebView清除导航历史记录

iOS 管理域模型和 NSManagedObject 模型