If we want to get the x-cordinate of origin of the view, then we need to write like:
view.frame.origin.x
For width, we need to write:
view.frame.size.width
But if we add a simple extension to an UIView
, we can get all the attributes very simply, like:
view.x
view.y
view.width
view.height
It will also help setting these attributes like:
view.x = 10
view.y = 10
view.width = 100
view.height = 200
And the simple extension would be:
extension UIView {
var x: CGFloat {
get {
return self.frame.origin.x
}
set {
self.frame = CGRect(x: newValue, y: self.frame.origin.y, width: self.frame.size.width, height: self.frame.size.height)
}
}
var y: CGFloat {
get {
return self.frame.origin.y
}
set {
self.frame = CGRect(x: self.frame.origin.x, y: newValue, width: self.frame.size.width, height: self.frame.size.height)
}
}
var width: CGFloat {
get {
return self.frame.size.width
}
set {
self.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: newValue, height: self.frame.size.height)
}
}
var height: CGFloat {
get {
return self.frame.height
}
set {
self.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: self.frame.size.width, height: newValue)
}
}
}
We need to add this class file in a project and it'll be available to use throughout the project!