在 Objective C 中,很容易使用强制转换来改变UIView
基于标签的图像(UIImageView*)
——比如:
[ (UIImageView*) [self.view viewWithTag:n+1] setImage:[UIImage imageNamed:@"bb.png"]];
我一直在尝试找到一个可以在 Swift 3 中做同样事情的最新示例。我终于找到了解决方案——你需要使用as! 关键字和可选的强制转换为UIImageView?
. 如果你需要这样做——这里有一些工作代码:
// SWIFT3 change UIView based on viewWithTag (johnrpenner, toronto)
override func viewDidLoad()
{
super.viewDidLoad()
var n : Int = 0
for i in stride(from:7, to:-1, by:-1) {
for j in 0...7 {
n = i*8+j
let sqImageView = UIImageView(image: UIImage(named: "wp.png"))
sqImageView.tag = n+1
sqImageView.frame.origin.x = (CGFloat(j) * cellX + xStartAdj)
sqImageView.frame.origin.y = ( (CGFloat(7-i) * cellY) + yStartAdj )
view.addSubview(sqImageView)
}
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
//func touchesBegan(touches: Set<UITouch>, with event: UIEvent?)
{
if let touch = touches.first {
let touchPos = touch.location(in: self.view) //swift3
let touchSQ : Int = coordToSQ(touchPoint:touchPos)
// change UIView.image based on viewWithTag
if var findView : UIImageView = view.viewWithTag(touchSQ+1) as! UIImageView? { findView.image = UIImage(named: "bp.png")! }
}
}
无论如何——花了几个小时才弄清楚这一点,而且所有的东西都适用于 Swift 2 或 Objective C——我认为 Swift 3 的例子可能有用。
干杯!约翰·p