如何在故事板上使UIImageView可点击(swift)
我是新来的swift(和一般的Xcode开发),我想知道如何使故事板上的ImageView可点击。 我想要做的就是让它点击时,它显示另一个视图控制器。
你可以添加tapGesture。 这里是代码:
class ViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() // create tap gesture recognizer let tapGesture = UITapGestureRecognizer(target: self, action: "imageTapped:") // add it to the image view; imageView.addGestureRecognizer(tapGesture) // make sure imageView can be interacted with by user imageView.userInteractionEnabled = true } func imageTapped(gesture: UIGestureRecognizer) { // if the tapped view is a UIImageView then set it to imageview if let imageView = gesture.view as? UIImageView { println("Image Tapped") //Here you can initiate your new ViewController } } }
Swift 3.0
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 } } }
我build议创build一个没有文本的UIButton,并将其制作为你想要的图像。 这样做后,你可以按CTRL拖动图像到你想继续的视图控制器。 或者你可以在你的视图控制器的代码中进行一个IBAction,手动调整。
你可以做到这一点更容易,并通过故事板可以点击图像,根本没有编码 。
- 首先,您需要将
UITapGestureRecognizer
拖到Storyboard中的UIImageView
中。 - 然后你创build你想在你的代码中运行的IBAction
@IBAction func imageClicked(_ sender: Any) {}
- 接下来,需要通过select
Document Outline
的手势识别器,将UITapGestureRecognizer
连接到IBAction
,然后切换到“Connection Inspector Tab
然后将“Sent Actions
– >“Selector
拖动到您的UIViewController
中,然后select您创build的相应操作先前。 - 最后,您必须在图像视图上设置checkbox
User Interaction Enabled
。
完成,一个完全可点击的UIImageView,无需编写一行代码,除非您想要调用的显而易见的function。 但是,嘿,如果你想例如推一个segue,那么你可以通过使用手势识别器Triggered Segues
而不是使用Sent Actions
来完成编码。
尽pipeStoryboard有其局限性,但是不需要为可点击图片编写代码。 ;)
在故事板上设置图像视图用户交互启用,然后用此方法获取
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; if ([touch view] == yourImageView) { //add your code for image touch here } }
对于swift版本3.0,请尝试下面的代码
override func viewDidLoad() { super.viewDidLoad() let tap1 = UITapGestureRecognizer(target: self, action: #selector(tapGesture1)) imageview.addGestureRecognizer(tap1) imageview.isUserInteractionEnabled = true } func tapGesture1() { print("Image Tapped") }