您好,登錄后才能下訂單哦!
要實現類似Photos app的圖片選擇器,可以通過使用UIImagePickerController類以及UICollectionView來實現。下面是一個簡單的示例代碼:
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)
}
}
通過以上代碼,你可以實現一個簡單的圖片選擇器,并用UICollectionView展示選中的圖片。你可以根據需求進一步自定義UI和功能。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。