我有一个视图控制器,我在其中添加多个自定义视图。我想要做的是访问我动态添加的视图,并在某些触发器(如位置更新)上访问它。
如下所示...我已经简化了一些代码。但这应该会让你对我想要实现的目标有一个相当好的看法。
class MapViewController: UIViewController, UIScrollViewDelegate, UITextFieldDelegate, CLLocationManagerDelegate {
//my custom views
var mapPins = Set<UserPin>()
override func viewDidLoad() {
createScreen()
updateScreen() //this happens on location update
super.viewDidLoad()
}
func createScreen() {
let userPinA = UserPin(userID: "ab12319ssdf91dfa2js92kajsdf23kd93", name: "J smith", posX: Int(1500), posY: Int(1800), pictureURL: "sad_face.jpg", direction: 1, colour: "Red", currentTrack: 33, lastTimeConnected: Date())
mapPins.insert(userPinB)
//this is actually done dynamically but good enough for the example
mapPins.insert(userPinB)
mapPins.insert(userPinC)
mapPins.insert(userPinD)
containerView = UIView()
// adding is not a problem. So far so good!
for userpin in mapPins
{
imageView.addSubview(userpin)
}
containerView.addSubview(imageView)
scrollView.addSubview(containerView)
view.addSubview(scrollView)
}
//triggered on location update, just believe it fires for the purpose of this
func updateScreen()
{
//Here is the issue!
//I want to get to the right view by userID, the same that is updated on my mapPins set, and update the posX and posY (animation is the intention). How do I do that?
//something like self.view.subviews.view.userID, obviously that does not work. I just don't think I understand enough how custom views work to access the properties of them.
}
这是我的自定义视图的外观。正如您可以看到它的简单视图。 userID字段是我真正感兴趣的字段。
import UIKit
class UserPin: UIView {
var userID : String?
var name : String?
var posX : Int?
var posY : Int?
var pictureURL : String?
var direction : Int?
var colour : String?
var currentTrack : Int?
var lastTimeConnected : Date?
init(userID: String, name: String, posX: Int, posY: Int, pictureURL: String, direction: Int, colour: String, currentTrack : Int, lastTimeConnected : Date)
{
self.userID = userID
self.name = name
self.posX = posX
self.posY = posY
self.pictureURL = pictureURL
self.direction = direction
self.colour = colour
self.currentTrack = currentTrack
self.lastTimeConnected = lastTimeConnected
super.init(frame: CGRect(x: posX, y: posY, width: 100, height: 100))
self.addControls(userID, name: name, posX: posX, posY: posY, pictureURL: pictureURL, direction: direction, colour: colour, currentTrack: currentTrack, lastTimeConnected: lastTimeConnected)
}
func addControls(_ userID: String, name: String, posX: Int, posY: Int, pictureURL: String, direction: Int, colour: String, currentTrack : Int, lastTimeConnected : Date) {
//does stuff on the view with labels and shapes and stuff
}
答案 0 :(得分:1)
您可以在视图控制器中创建Dictionary
,其中密钥为userID
,对象为customView
s
如果有许多自定义视图,则效率会更高,因为Array
必须经常迭代。