溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何通過UIKit實現(xiàn)類似Photos app的圖片選擇器

發(fā)布時間:2024-05-31 11:38:09 來源:億速云 閱讀:95 作者:小樊 欄目:移動開發(fā)

要實現(xiàn)類似Photos app的圖片選擇器,可以通過使用UIImagePickerController類以及UICollectionView來實現(xiàn)。下面是一個簡單的示例代碼:

  1. 創(chuàng)建一個按鈕,點擊按鈕后打開圖片選擇器:
import UIKit

class ViewController: UIViewController, UIImagePickerControllerDelegate & UINavigationControllerDelegate {
    
    let imagePicker = UIImagePickerController()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let button = UIButton(frame: CGRect(x: 100, y: 100, width: 200, height: 50))
        button.setTitle("Select Image", for: .normal)
        button.addTarget(self, action: #selector(selectImage), for: .touchUpInside)
        view.addSubview(button)
        
        imagePicker.delegate = self
        imagePicker.allowsEditing = false
        imagePicker.sourceType = .photoLibrary
    }
    
    @objc func selectImage() {
        present(imagePicker, animated: true, completion: nil)
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[.originalImage] as? UIImage {
            //處理選中的圖片
        }
        
        dismiss(animated: true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        dismiss(animated: true, completion: nil)
    }
}
  1. 創(chuàng)建一個UICollectionView來展示選擇的圖片:
class ImageCollectionViewController: UICollectionViewController {
    
    var selectedImages: [UIImage] = []
    
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return selectedImages.count
    }
    
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as! ImageCell
        cell.imageView.image = selectedImages[indexPath.row]
        return cell
    }
}

class ImageCell: UICollectionViewCell {
    
    let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        contentView.addSubview(imageView)
    }
}

通過以上代碼,你可以實現(xiàn)一個簡單的圖片選擇器,并用UICollectionView展示選中的圖片。你可以根據(jù)需求進一步自定義UI和功能。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI