计算型的属性是通过类的其它属性赋值的过程自动赋值,先看一下代码
struct Size {
var width = 0.0
var height = 0.0
}
struct Point {
var x = 0.0
var y = 0.0
}
class Rectangle{
var origin = Point()
var size = Size()
var center: Point {
let centerX = origin.x + size.width/2
let centerY = origin.y + size.height/2
return Point(x: centerX, y: centerY)
}//计算型的属性
init( origin: Point , size: Size){
self.origin = origin;
self.size = size
}
}
这里的center属性就是计算型的属性,这个属性通过矩形的x、y、width、height属性赋值后自动赋值
此时给center属性赋值会报错
因为此时center属性是只读的,此时要想赋值,需要重写center属性的Set方法
class Rectangle{
var origin = Point()
var size = Size()
var center: Point {
get{
let centerX = origin.x + size.width/2
let centerY = origin.y + size.height/2
return Point(x: centerX, y: centerY)
}
set(newCenter){
origin.x = newCenter.x - size.width/2
origin.y = newCenter.y - size.height/2
}
}//计算型的属性
init( origin: Point , size: Size){
self.origin = origin;
self.size = size
}
}
此时赋值不会报错,并且会把x、y属性值进行修改
Set方法的优化写法,swift定义了好了newValue变量,可以重写Set方法,代码如下
class Rectangle{
var origin = Point()
var size = Size()
var center: Point {
get{
let centerX = origin.x + size.width/2
let centerY = origin.y + size.height/2
return Point(x: centerX, y: centerY)
}
set{
origin.x = newValue.x - size.width/2
origin.y = newValue.y - size.height/2
}
}//计算型的属性
init( origin: Point , size: Size){
self.origin = origin;
self.size = size
}
}
苹果官方定义矩形——CGRect
//苹果官方
var rect2 = CGRect(origin: CGPoint(x: 0,y: 0),size:CGSize(width: 10,height: 5))
rect2.origin
rect2.size
作者:u012903898 发表于2017/5/31 15:10:10 原文链接
阅读:170 评论:0 查看评论