我正在使用以下代码以编程方式创建我的视图:
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.width
3次,每次在控制台中打印0.0。怎么了?
答案 0 :(得分:2)
首先将statusfilterui
添加到父级。然后拨打statusfilterui.sizeToFit()
。它应该可以工作。
parentView.addSubview(statusfilterui)
statusfilterui.sizeToFit()