@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")
}
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
}
7 回答
你需要
UITapGestureRecognizer
. 要设置使用此:(您也可以使用UIButton并为其分配图像,没有文本,只需连接IBAction)
您需要添加一个手势识别器(用于点击使用UITapGestureRecognizer,用于点按并按住UILongPressGestureRecognizer)到您的
UIImageView
.并实现选择器方法,如:
您可以将
UITapGestureRecognizer
添加到imageView,只需将一个拖到Storyboard / xib中,然后从imageView拖动到gestureRecognizer,然后按Ctrl-拖动从gestureRecognizer到Swift文件即可生成IBAction
.您还需要在
UIImageView
上启用用户交互,如下图所示:对于swift 2.0及以上版本,请执行此操作
实际上你可以将
UIButton
的图像设置为通常放在UIImageView
中的图像 . 例如,你会做什么:你可以改为使用:
那么,这就是你的代码的样子:
使用此方法的好处是,如果必须从数据库加载图像,则可以在设置图像之前设置按钮的 Headers :
告诉您的用户您正在加载图片
您可以在
UIImageView
的顶部放置一个透明背景的UIButton
,并在加载图像之前先点按按钮Swift 4 Code
步骤1在ViewdidLoad()中
步骤2添加以下功能
经过测试和正常工作