我试着在用户点击的时候分配一个UIImageView给一个动作。

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


当前回答

你可以设置UIButton的图像到你通常会放在UIImageView中的图像。例如,你会这样做:

myImageView.image = myUIImage

你可以用:

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

下面是你的代码:

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
}

使用这个方法的好处是,如果你必须从数据库中加载图像,你可以在设置图像之前设置按钮的标题:

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

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

其他回答

斯威夫特这样做:

@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.isUserInteractionEnabled = true
}

func tappedMe() {
    print("Tapped on Image")
}

你需要添加一个手势识别器(对于点击使用UITapGestureRecognizer,对于点击和按住使用UILongPressGestureRecognizer)到你的UIImageView。

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

并像这样实现selector方法:

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

你可以在UIImageView上面放一个带有透明背景的UIButton,并在加载图像之前监听按钮上的点击

你需要一个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
}

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

Swift 4代码


步骤1在ViewdidLoad()中

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

步骤2添加“Following”功能

@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

    }

它已经过测试,工作正常