如何在Swift中使用nib文件实现独立的自定义UIView?

时间:2016-12-09 10:22:57

标签: uiview swift3 xib

很多时候我想实现自定义UIViews,但我总是遇到同样的问题:当我想使用它时,我的IBOutlets是零。

我尝试了我在网上看到的一切,但没有任何作用......

class ImagePickerView: UIView, ImagePickerDelegate {

@IBOutlet weak var imageViewSelected: UIImageView!


//MARK: - Initializers

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)

    let tapGesture = UILongPressGestureRecognizer(target: self, action:  #selector(self.onAddPicturePressed))
    tapGesture.minimumPressDuration = 0
    self.addGestureRecognizer(tapGesture)
}

override func awakeFromNib() {
    super.awakeFromNib()
    //imageViewSelected = UIImageView()
}


//MARK: - ImagePickerDelegate

func wrapperDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) {}

func doneButtonDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) {

    self.imageViewSelected.image = images[0] // (the limit is set to 1 image)
    imagePicker.dismiss(animated: true, completion: nil)
}

func cancelButtonDidPress(_ imagePicker: ImagePickerController) {
    imagePicker.dismiss(animated: true, completion: nil)
}


//MARK: - Events

func onAddPicturePressed(gesture: UITapGestureRecognizer) {
    if gesture.state == .began {
        self.backgroundColor = CustomsColors.gray
    } else if gesture.state == .ended {
        self.backgroundColor = CustomsColors.lightGray
    }

    showImagePicker()
}


//MARK: - Utils

func showImagePicker() {
    let imagePickerController = ImagePickerController()
    imagePickerController.delegate = self
    imagePickerController.imageLimit = 1
    Configuration.mainColor = CustomsColors.green
    Configuration.cancelButtonTitle = "Annuler"
    Configuration.doneButtonTitle = "OK"
    Configuration.noImagesTitle = "Pas d'images disponibles"

    self.parentViewController?.present(imagePickerController, animated: true, completion: nil)
}
}

我试过self = Bundle.main.loadNibNamed("ImagePickerView", owner: self, options: nil)?.first as! ImagePickerView,但我不能自我。

我想要一些非常简单的东西,但我不知道该怎么做......

1 个答案:

答案 0 :(得分:0)

按照以下步骤添加nib视图控制器:

  1. 制作对象:

    var priceView:FV_ViewToShowPrice!

  2. Give Frame:

    priceView = Bundle.main.loadNibNamed(" FV_ViewToShowPrice&#34 ;, owner:self,options:nil)![0] as! FV_ViewToShowPrice

    priceView.frame = self.view.bounds

  3. 添加视图:

    self.view.addSubview(priceView)