专业java、php、iOS、C++、网页设计、平面设计、网络营销、游戏开发、前端与移动开发培训机构

照片选择器自定义cell

  • 系统没有提供对应的cell.需要自定义

    • 新建 HMPhotoSelectorCell 继承 UICollectionViewCell

      /// 自定义cell
      class HMPhotoSelectorCell: UICollectionViewCell {
      
        // MARK: - 构造函数
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
      
        override init(frame: CGRect) {
            super.init(frame: frame)
        }
      }
      
    • HMPhotoSelectorCell 懒加载控件

      // MARK: - 懒加载控件
      /// 加号按钮
      private lazy var addButton: UIButton = {
        let button = UIButton()
      
        button.setImage(UIImage(named: "compose_pic_add"), for: UIControlState.normal)
      
        return button
      }()
      
      /// 删除按钮
      private lazy var deleteButton: UIButton = {
        let button = UIButton()
      
        button.setImage(UIImage(named: "compose_photo_close"), for: UIControlState.normal)
      
        return button
      }()
      
    • HMPhotoSelectorCell 添加 setupUI

      override init(frame: CGRect) {
        super.init(frame: frame)
      
        setupUI()
      }
      
      // MARK: - 准备UI
      /// 准备UI
      private func setupUI() {
        // 添加子控件
        contentView.addSubview(addButton)
        contentView.addSubview(deleteButton)
      
        // 添加约束
        // 作为独立工程最好少依赖第三方框架
        addButton.translatesAutoresizingMaskIntoConstraints = false
        deleteButton.translatesAutoresizingMaskIntoConstraints = false
      
        let viewDicts = ["ab": addButton, "rb": deleteButton]
        // 添加按钮
        contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[ab]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDicts))
        contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[ab]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDicts))
      
        // 删除按钮
        // 水平方向在父控件右边一定距离
        contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[rb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDicts))
      
        // 垂直方向在父控件顶部一定距离
        contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[rb]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDicts))
      }
      
    • 修改注册的cell
      // 注册cell
      collectionView!.registerClass(HMPhotoSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
      

results matching ""

    No results matching ""