简体   繁体   English

如何识别我点击了哪个UIImageview?

[英]How recognize which UIImageview I've tapped?

I want to realize a sort of matrix editable by touch. 我想实现一种可通过触摸编辑的矩阵。 A series of black or white cell that if tapped switch form black to withe or viceversa. 一系列黑色或白色单元格,如果轻按开关可形成黑色或相反。 For doing this i will use UIImageView arranged in stack view a Tap Gesture Recognizer. 为此,我将使用排列在堆栈视图中的UIImageView轻击手势识别器。 But how do I know which UIImageView was tapped? 但是我怎么知道哪个UIImageView被点击了呢? And in which way I can change the UIImage in the UIImageView? 我可以通过哪种方式在UIImageView中更改UIImage?

If they are just white and black, it would be much simpler to use a UIView and set its backgroundColor to .white or .black . 如果他们只是白色和黑色,这将是更易于使用一个UIView ,并设置其backgroundColor.white.black You can use the tag property of the UIView s to identify them. 您可以使用UIViewtag属性来识别它们。

In your gestureRecognizer handler, the recognizer.view tells you the view that triggered the gesture. 在你gestureRecognizer处理程序,则recognizer.view告诉你的view是触发了该姿势。

You can assign the tags in Interface Builder . 您可以在Interface Builder中分配标签。 For example, if you have an 8x8 array of squares, you could use a 2-digit number where the first digit is the row and the second digit is the column. 例如,如果您有一个8x8的正方形数组,则可以使用2位数字,其中第一个数字是行,第二个数字是列。 Thus, your tags would be 11 , 12 , ..., 87 , 88 . 因此,您的代码将是1112 ,..., 8788

func squareTapped(recognizer: UIGestureRecognizer) {
    if let view = recognizer.view {
        let tag = view.tag
        let row = tag / 10
        let col = tag % 10
        print("The view at row \(row), column \(col) was tapped")

        if view.backgroundColor == .black {
            view.backgroundColor = .white
        } else {
            view.backgroundColor = .black
        }
    }
}

If you do want to use images, then load the images as properties of your viewController and assign them based upon the row and column of your image. 如果确实要使用图像,则将图像作为viewController的属性加载,并根据图像的行和列进行分配。 Here I have used an Outlet Collection to hold all of the UIImageView s. 在这里,我使用了一个Outlet Collection来保存所有UIImageView In Interface Builder , you'd connect each of your cells to the squares property. Interface Builder中 ,将每个单元格连接到squares属性。

class BoardViewController: UIViewController {
    let blackImage = UIImage(named: "blackImage")!
    let whiteImage = UIImage(named: "whiteImage")!
    @IBOutlet var squares: [UIImageView]!
    var recognizersAdded = false

    func setUpBoard() {
        for imageview in squares {
            if !recognizersAdded {
                let recognizer = UITapGestureRecognizer(target: self, action: #selector(squareTapped))
                imageview.addGestureRecognizer(recognizer)
                imageview.isUserInteractionEnabled = true
            }

            let tag = view.tag
            let row = tag / 10
            let col = tag % 10

            // Just for demo purposes, set up a checkerboard pattern
            if (row + col) % 2 == 0 {
                imageview.image = blackImage
            } else {
                imageview.image = whiteImage
            }
        }
        recognizersAdded = true
    }

    func squareTapped(recognizer: UIGestureRecognizer) {
        if let view = recognizer.view as? UIImageView {
            let tag = view.tag
            let row = tag / 10
            let col = tag % 10
            print("The view at row \(row), column \(col) was tapped")

            if view.image == blackImage {
                view.image = whiteImage
            } else {
                view.image = blackImage
            } 
        }
    }
}

Assign a tag to each UIImageView and Add Tap gestures on them. 为每个UIImageView分配一个标签,并在其上添加Tap手势。

Upon tap on any view , you can get the image view tapped by : 点击任意视图时,可以通过以下方式点击图像视图:

UIImageView *imageView = gestureRecogniser.view

The code I'm using now is this, it works well. 我现在使用的代码是这样,它运行良好。 But I want to use a pan gesture (UIPanGetureRecognizer) to change colors of the UIView. 但是我想使用平移手势(UIPanGetureRecognizer)更改UIView的颜色。 How can I do? 我能怎么做?

class ViewController: UIViewController {
@IBOutlet weak var PrincipalRowStack: UIStackView!

let rowsNumber=10
let colsNumber=10

override func viewDidLoad() {
    // Do any additional setup after loading the view, typically from a nib.


    super.viewDidLoad()

    var rowsStack = [UIStackView]()
    var images = [[UIView]]()
    var gestRec = [[UITapGestureRecognizer]]()
    for r in 0...rowsNumber-1 {
        rowsStack.append(UIStackView())
        rowsStack[r].axis = .horizontal
        rowsStack[r].distribution = .fillEqually
        images.append([UIView]())
        gestRec.append([UITapGestureRecognizer]())
        for c in 0...colsNumber-1{
            images[r].append(UIView())
            gestRec[r].append(UITapGestureRecognizer())
            gestRec[r][c].addTarget(self, action: #selector(ViewController.Tap(_:)))
            images[r][c].contentMode = .scaleToFill
            images[r][c].layer.borderWidth = 1
            images[r][c].layer.borderColor = UIColor(red:0.5, green:0.5, blue:0.5, alpha: 1.0).cgColor
            images[r][c].addGestureRecognizer(gestRec[r][c])
            rowsStack[r].addArrangedSubview(images[r][c])
        }
    }
    for s in rowsStack{
        PrincipalRowStack.addArrangedSubview(s)
    }

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}



func Tap(_ recognizer: UITapGestureRecognizer) {

    if let view = recognizer.view {
        //let tag = view.tag
        //let row = tag / 10
        //let col = tag % 10
        print("Tapped!")

        if view.backgroundColor == .black {
            view.backgroundColor = .white
        } else {
            view.backgroundColor = .black
        }
    }

}
}

I'solved adding a PanGestureRecognizer to the principalStackView and than i use this function with a hitTest to know which view should change color. 我解决了将PanGestureRecognizer添加到PrincipalStackView的问题,然后我将此函数与hitTest一起使用,以了解哪个视图应该更改颜色。

func pan(_ recognizer: UIPanGestureRecognizer){
    if (recognizer.state == .began ||
        recognizer.state == .changed)
    {
        let loc = recognizer.location(in: principalRowStack)
        let view = principalRowStack.hitTest(loc, with: UIEvent())
        view?.backgroundColor = .black


    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM