【发布时间】:2020-10-06 22:41:35
【问题描述】:
所以我创建了这个 UIButton 子类。它是一个可重用的组件,可以添加到任何视图控制器中。我需要通过点击按钮来呈现一个警报视图控制器。所以基本上我需要找出按钮所在的视图控制器,以便我可以将视图控制器作为参数传递。
final class ProfileButton: UIButton {
let picker = UIImagePickerController()
lazy var shadowImageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
imageView.image = UIImage(named: "download")
return imageView
}()
override public init(frame: CGRect) {
super.init(frame: frame)
setupSelf()
self.addTarget(self, action: #selector(profileButtonTapped), for: .touchUpInside)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override public func layoutSubviews() {
super.layoutSubviews()
shadowImageView.layer.cornerRadius = self.frame.width/2.70
shadowImageView.layer.masksToBounds = true
}
@objc func profileButtonTapped(){
imageHandler(presenter: )
}
@objc func imageHandler(presenter: UIViewController!){
let alertController = UIAlertController(title: "Profile Picture", message: "Please select your profile picture", preferredStyle: .alert)
let okAction = UIAlertAction(title: "Photo Library", style: .default, handler: { (action: UIAlertAction!) in
print("I am working")
})
let cameraAction = UIAlertAction(title: "Camera", style: .default, handler: { (action: UIAlertAction!) in
print("I am working")
})
alertController.addAction(okAction)
alertController.addAction(cameraAction)
presenter.present(alertController, animated: true, completion: nil)
}
我实际上需要找出视图控制器,以便我可以将它传递给 imageHandler(presenter: UIViewController) 函数。
【问题讨论】:
-
为什么不在视图控制器中使用
addTarget(selector:)? -
如果我有 20 个创建此对象的视图控制器。在每个视图控制器中添加目标是没有意义的。
标签: ios swift uiview uiviewcontroller uibutton