ios 如何在 Swift 中为 UIImageView 对象分配一个动作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27880607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 04:17:58  来源:igfitidea点击:

How to assign an action for UIImageView object in Swift

iosswiftuiimageview

提问by user3706773

I'm trying to assign an UIImageViewto an action when the user taps it.

UIImageView当用户点击它时,我试图为它分配一个动作。

I know how to create an action for a UIButton, but how could I mimic the same behavior of a UIButton, but using a UIImageView?

我知道如何为 a 创建一个动作UIButton,但是我怎么能模仿 a 的相同行为UIButton,但是使用 aUIImageView呢?

回答by Aseider

You'll need a UITapGestureRecognizer. To set up use this:

你需要一个UITapGestureRecognizer. 要设置使用这个:

override func viewDidLoad()
{
    super.viewDidLoad()

    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
    imageView.isUserInteractionEnabled = true
    imageView.addGestureRecognizer(tapGestureRecognizer)
}

@objc func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
    let tappedImage = tapGestureRecognizer.view as! UIImageView

    // Your action
}

(You could also use a UIButtonand assign an image to it, without text and than simply connect an IBAction)

(你也可以使用 aUIButton并为其分配一个图像,没有文本,而不是简单地连接一个IBAction

回答by Midhun MP

You need to add a a gesture recognizer (For tap use UITapGestureRecognizer, for tap and hold use UILongPressGestureRecognizer) to your UIImageView.

您需要添加AA手势识别(对于自来水的使用UITapGestureRecognizer,为点住用UILongPressGestureRecognizer)到您UIImageView

let tap = UITapGestureRecognizer(target: self, action: #selector(YourClass.tappedMe))
imageView.addGestureRecognizer(tap)
imageView.isUserInteractionEnabled = true

And Implement the selector method like:

并实现选择器方法,如:

@objc func tappedMe()
{
    println("Tapped on Image")
}

回答by Emil

You can add a UITapGestureRecognizerto the imageView, just drag one into your Storyboard/xib, Ctrl-drag from the imageView to the gestureRecognizer, and Ctrl-drag from the gestureRecognizer to the Swift-file to make an IBAction.

您可以向UITapGestureRecognizerimageView添加一个,只需将一个拖到您的 Storyboard/xib 中,按住 Ctrl 从 imageView 拖动到gestureRecognizer,然后按住 Ctrl 从gestureRecognizer 拖动到 Swift 文件以制作IBAction.

You'll also need to enable user interactions on the UIImageView, as shown in this image: enter image description here

您还需要在 上启用用户交互UIImageView,如下图所示: 在此处输入图片说明

回答by Abhishek Kumar

For swift 2.0 and above do this

对于 swift 2.0 及更高版本,请执行此操作

@IBOutlet weak var imageView: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.tappedMe))
        imageView.addGestureRecognizer(tap)
        imageView.userInteractionEnabled = true
    }
    func tappedMe()
    {
        print("Tapped on Image")
    }

回答by Ravindra_Bhati

Swift4 Code

Swift4 代码

Try this some new extension methods:

试试这个一些新的扩展方法:

import UIKit

extension UIView {

    fileprivate struct AssociatedObjectKeys {
        static var tapGestureRecognizer = "MediaViewerAssociatedObjectKey_mediaViewer"
    }

    fileprivate typealias Action = (() -> Void)?


    fileprivate var tapGestureRecognizerAction: Action? {
        set {
            if let newValue = newValue {
                // Computed properties get stored as associated objects
                objc_setAssociatedObject(self, &AssociatedObjectKeys.tapGestureRecognizer, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
            }
        }
        get {
            let tapGestureRecognizerActionInstance = objc_getAssociatedObject(self, &AssociatedObjectKeys.tapGestureRecognizer) as? Action
            return tapGestureRecognizerActionInstance
        }
    }


    public func addTapGestureRecognizer(action: (() -> Void)?) {
        self.isUserInteractionEnabled = true
        self.tapGestureRecognizerAction = action
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture))
        self.addGestureRecognizer(tapGestureRecognizer)
    }


    @objc fileprivate func handleTapGesture(sender: UITapGestureRecognizer) {
        if let action = self.tapGestureRecognizerAction {
            action?()
        } else {
            print("no action")
        }
    }

}

Now whenever we want to add a UITapGestureRecognizerto a UIViewor UIViewsubclass like UIImageView, we can do so without creating associated functions for selectors!

现在,无论何时我们想要将 a 添加UITapGestureRecognizer到 aUIViewUIView子类 like UIImageView,我们都可以在不为选择器创建关联函数的情况下这样做!

Usage:

用法:

 profile_ImageView.addTapGestureRecognizer {
        print("image tapped")
    }

回答by Jojodmo

You could actually just set the image of the UIButtonto what you would normally put in a UIImageView. For example, where you would do:

实际上,您可以将 的图像设置为UIButton通常放在UIImageView. 例如,你会在哪里做:

myImageView.image = myUIImage

You could instead use:

您可以改为使用:

myButton.setImage(myUIImage, forState: UIControlState.Normal)

So, here's what your code could look like:

因此,您的代码可能如下所示:

override func viewDidLoad(){
  super.viewDidLoad()

  var myUIImage: UIImage //set the UIImage here
  myButton.setImage(myUIImage, forState: UIControlState.Normal)
}

@IBOutlet var myButton: UIButton!
@IBAction func buttonTap(sender: UIButton!){
  //handle the image tap
}

The great thing about using this method is that if you have to load the image from a database, you could set the title of the button before you set the image:

使用此方法的好处在于,如果您必须从数据库加载图像,则可以在设置图像之前设置按钮的标题:

myButton.setTitle("Loading Image...", forState: UIControlState.Normal)

To tell your users that you are loading the image

告诉您的用户您正在加载图像

回答by candyline

Need to add lazy for TapGestureRecognizer to register
since the 'self' in UITapGestureRecognizer(target: self ...) will be nil if it's not a lazy var. Even if you set isUserInteractionEnable = true, it won't register without lazy var.

需要为 TapGestureRecognizer 添加惰性以进行注册,
因为 UITapGestureRecognizer(target: self ...) 中的 'self' 如果不是惰性变量,则为零。即使您设置 isUserInteractionEnable = true,它也不会在没有惰性变量的情况下注册。

lazy var imageSelector : UIImageView = {
    let image = UIImageView(image: "imageName.png")
    //now add tap gesture
    image.isUserInteractionEnabled = true
    image.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleImageSelector)))
    return image
}()
@objc private func handleImageSelector() {
    print("Pressed image selector")
}

回答by Sachin Rasane

Swift 4 Code

斯威夫特 4 代码



Step 1 In ViewdidLoad()

第 1 步在 ViewdidLoad()

   let pictureTap = UITapGestureRecognizer(target: self, action: #selector(MyInfoTableViewController.imageTapped))
       userImageView.addGestureRecognizer(pictureTap)
       userImageView.isUserInteractionEnabled = true

Step 2 Add Following Function

Step 2 添加以下功能

@objc func imageTapped() {

        let imageView = userImageView
        let newImageView = UIImageView(image: imageView?.image)
        newImageView.frame = UIScreen.main.bounds
        newImageView.backgroundColor = UIColor.black
        newImageView.contentMode = .scaleAspectFit
        newImageView.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(dismissFullscreenImage))
        newImageView.addGestureRecognizer(tap)
        self.view.addSubview(newImageView)

        self.navigationController?.isNavigationBarHidden = true
        self.tabBarController?.tabBar.isHidden = true

    }

It's Tested And Working Properly

它已经过测试并且工作正常

回答by depsch ali

You can put a UIButtonwith a transparent background over top of the UIImageView, and listen for a tap on the button before loading the image

您可以UIButton在 顶部放置一个带有透明背景的UIImageView,并在加载图像之前聆听按钮上的点击

回答by levan

I suggest to place invisible(opacity = 0) button on your imageview and then handle interaction on button.

我建议在您的图像视图上放置不可见(不透明度 = 0)按钮,然后处理按钮上的交互。