gpt4 book ai didi

swift - 在 Swift3 中基于 viewWithTag 更改 UIView

转载 作者:搜寻专家 更新时间:2023-10-31 22:44:21 24 4
gpt4 key购买 nike

在 Objective C 中,很容易根据使用转换为 (UIImageView*) 的标记更改 UIView 的图像 — 类似于:

[ (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 的例子可能会有用。

干杯!约翰·普

最佳答案

就是这样。

if let findView = self.view.viewWithTag(touchSQ+1) as? UIImageView {
findView.image = UIImage(named: "bp.png")
}

关于swift - 在 Swift3 中基于 viewWithTag 更改 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40624956/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com