【问题标题】:How to add an action for when an image is clicked? [duplicate]单击图像时如何添加操作? [复制]
【发布时间】:2019-01-30 15:03:51
【问题描述】:

我正在尝试在我的应用中使用自定义图像作为按钮。如何为图像添加操作?

这适用于 iOS 应用程序,我不想将默认文本按钮用作按钮。我已经尝试控制+拖动图像到 ViewController 但没有“操作”选项。

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

    let designChoice = designPrac.randomElement()
    let forChoice = forWhatPrac.randomElement()
    let helpChoice = toHelpPrac.randomElement()

    designLabel.text = designChoice
    forLabel.text = forChoice
    helpLabel.text = helpChoice
}

这是我在应用启动时必须运行的代码,但我找不到在单击图像按钮时让它工作的方法。

【问题讨论】:

  • 什么图片?您发布的代码似乎与您的问题无关?为什么不在你的图片中使用UIButton
  • 您是否尝试过在图像上制作相同大小的 UIButton 并仅删除“按钮”文本?你试过在 UIImageView 上点击手势吗?
  • 我不确定您的图像“使用 UIButton”是什么意思。我是 Swift 的新手,对我的无知感到抱歉。我知道如何向情节提要添加按钮,但不知道如何使其成为我在 Assets.xcassets 中的图像。如何使用点击手势?
  • @bluewizard3 一个普通的 UIButton 可以有一个图像而不是一个标题。
  • stackoverflow.com/questions/27880607/… -> 在imageview上添加点击手势并处理imageview的动作,我们也可以使用UIView的所有子视图。

标签: ios swift button action


【解决方案1】:

为了给UIImageView添加一个动作,你需要给它添加一个UITapGestureRecognizer,你可以这样做:

<#YourImageView#>.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.handleImageTap)))

然后你可以使用选择器来处理点击:

@objc func handleImageTap() {
    // handle image tap here    
}

【讨论】:

  • 因此,我猜想为UIImageView 添加一个出口,然后用它的名字代替 ?
  • 是的,别忘了设置约束。并且在其上放置图像进行测试会使事情变得更容易。
  • 设置约束是什么意思?
【解决方案2】:

您可以为此目的使用 addGestureRecognizer:

let imageView = UIImageView()
//add necessary code 
imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(MethodForAction)))

【讨论】:

    【解决方案3】:

    根据How do you make an UIImageView on the storyboard clickable (swift)

    class ViewController: UIViewController {
    
    @IBOutlet weak var imageView: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // create tap gesture recognizer
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.imageTapped(gesture:)))
    
        // add it to the image view;
        imageView.addGestureRecognizer(tapGesture)
        // make sure imageView can be interacted with by user
        imageView.isUserInteractionEnabled = true
    }
    
    func imageTapped(gesture: UIGestureRecognizer) {
        // if the tapped view is a UIImageView then set it to imageview
        if (gesture.view as? UIImageView) != nil {
            print("Image Tapped")
            //Here you can initiate your new ViewController
    
        }
    }
    

    【讨论】:

    • 不应简单地复制别人的答案,而应将问题作为副本关闭。
    • 我认为我没有足够的代表将其标记为重复。如果我这样做,我不知道该怎么做......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-13
    • 1970-01-01
    • 2016-01-17
    • 1970-01-01
    • 2021-08-16
    相关资源
    最近更新 更多