Swift 3 - 如何比较UIImage的宽度和高度?
Swift 3 - How to compare UIImage width and height?
我需要比较UIImage的宽度和高度,当宽度大于高度时,我会添加边框。下面是我在 cocoa touch class
上的代码
override func viewDidLoad() {
let x = p2Image.image?.size.width
let y = p2Image.image?.size.height
if x > y{
p2Border.backgroundColor = UIColor.black
}else{
p2Border.backgroundColor = UIColor.clear
}
}
提示错误Binary operator > cannot apply to two CGFloats operand, leave help me..
由于 可选链接,您的 x
和 y
是可选的,因此您需要将它们解包。 可选绑定 是一种安全的方式:
override func viewDidLoad() {
if let x = p2Image.image?.size.width,
let y = p2Image.image?.size.height {
if x > y {
p2Border.backgroundColor = .black
} else {
p2Border.backgroundColor = .clear
}
}
}
如果 p2Image.image
是 nil
,这将安全地不做任何事情。
如果要在 p2Image.image
为 nil
时分配 .clear
,则可以将 可选绑定 与 x > y
像这样比较:
override func viewDidLoad() {
if let x = p2Image.image?.size.width,
let y = p2Image.image?.size.height,
x > y {
p2Border.backgroundColor = .black
} else {
p2Border.backgroundColor = .clear
}
}
我需要比较UIImage的宽度和高度,当宽度大于高度时,我会添加边框。下面是我在 cocoa touch class
上的代码override func viewDidLoad() {
let x = p2Image.image?.size.width
let y = p2Image.image?.size.height
if x > y{
p2Border.backgroundColor = UIColor.black
}else{
p2Border.backgroundColor = UIColor.clear
}
}
提示错误Binary operator > cannot apply to two CGFloats operand, leave help me..
由于 可选链接,您的 x
和 y
是可选的,因此您需要将它们解包。 可选绑定 是一种安全的方式:
override func viewDidLoad() {
if let x = p2Image.image?.size.width,
let y = p2Image.image?.size.height {
if x > y {
p2Border.backgroundColor = .black
} else {
p2Border.backgroundColor = .clear
}
}
}
如果 p2Image.image
是 nil
,这将安全地不做任何事情。
如果要在 p2Image.image
为 nil
时分配 .clear
,则可以将 可选绑定 与 x > y
像这样比较:
override func viewDidLoad() {
if let x = p2Image.image?.size.width,
let y = p2Image.image?.size.height,
x > y {
p2Border.backgroundColor = .black
} else {
p2Border.backgroundColor = .clear
}
}