Amir_P Amir_P - 3 months ago 18
iOS Question

View is showing but printing width shows 0

I'm creating my view programmatically with this code :

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)


And I want center my statusfilterui by getting width of view but the problem is I'm printing
statusfilterui.frame.width
3 times and every time its printing 0.0 in console. what is wrong?

Answer

Add statusfilterui to parent first. Then call statusfilterui.sizeToFit(). It should then work.

parentView.addSubview(statusfilterui)
statusfilterui.sizeToFit()

Apple doc on sizeToFit()