ios - objective - swift4 image



如何在故事板上使UIImageView可點擊(swift) (4)

在故事板上設置圖像視圖用戶交互啟用,然後用此方法獲取

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{
    UITouch *touch = [touches anyObject];

    if ([touch view] == yourImageView)
    {
            //add your code for image touch here 
    }
}

我是新來的swift(和一般的Xcode開發),我想知道如何使故事板上的ImageView可點擊。 我想要做的就是讓它點擊時,它顯示另一個視圖控制器。


Answer #1

我建議創建一個沒有文本的UIButton,並將其製作為你想要的圖像。 這樣做後,你可以按CTRL拖動圖像到你想繼續的視圖控制器。 或者你可以在你的視圖控制器的代碼中進行一個IBAction,手動調整。


Answer #2

你可以添加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

        }
    }
}

Answer #3

你可以做到這一點更容易,並通過故事板可以點擊圖像,沒有任何編碼

  • 首先,您需要將UITapGestureRecognizer拖到Storyboard中的UIImageView中。
  • 然後你創建你想在你的代碼中運行的IBAction @IBAction func imageClicked(_ sender: Any) {}
  • 接下來,需要通過選擇Document Outline的手勢識別器,將UITapGestureRecognizer連接到IBAction ,然後切換到“ Connection Inspector Tab然後將“ Sent Actions - >“ Selector拖動到您的UIViewController中,然後選擇您創建的相應操作先前。
  • 最後,您必須在圖像視圖上設置複選框User Interaction Enabled

完成,一個完全可點擊的UIImageView,無需編寫一行代碼,除非您想要調用的顯而易見的功能。 但是,嘿,如果你想例如推一個segue,那麼你可以通過使用手勢識別器Triggered Segues來代替它的Sent Actions而不用編碼。

儘管Storyboard有其局限性,但是不需要為可點擊圖片編寫代碼。 ;)





uiimageview