您好,登錄后才能下訂單哦!
要實現(xiàn)類似Photos app的圖片選擇器,可以通過使用UIImagePickerController類以及UICollectionView來實現(xiàn)。下面是一個簡單的示例代碼:
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)
}
}
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和功能。
免責聲明:本站發(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)容。