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

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


当前回答

斯威夫特这样做:

@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")
}

其他回答

@IBOutlet weak var imageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
//ViewController is your current view controller    
let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.tappedMe))
    imageView.addGestureRecognizer(tap)
    imageView.isUserInteractionEnabled = true
}

// Need to ass objective-c annotation 
@objc
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")
}

斯威夫特这样做:

@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")
}

你可以设置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)

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

你可以添加一个UITapGestureRecognizer到imageView中,只需将一个拖到你的Storyboard/xib中,从imageView中按住ctrl拖动到gestureRecognizer中,再从gestureRecognizer中按住ctrl拖动到swift文件中,即可生成IBAction。

你还需要在UIImageView上启用用户交互,如下图所示: