使用swift在另一个类中使用IBAction调用函数

时间:2015-01-21 22:09:07

标签: ios swift uiimage uitextview screenshot

class EditTextViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UIPopoverPresentationControllerDelegate, UITextViewDelegate, UIDocumentInteractionControllerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

@IBOutlet weak var textView: UITextView!
@IBOutlet var contentImageView: UIImageView!

        func imageForTextView(UIView) -> UIImage {

        UIGraphicsBeginImageContextWithOptions(textView.bounds.size, false, 0)

        view.layer.renderInContext(UIGraphicsGetCurrentContext())
        var image = UIGraphicsGetImageFromCurrentImageContext() as UIImage
        UIGraphicsEndImageContext()

//        println(image)
        return image
    }        
}

以上代码具有我试图调用的功能。 imageForTextView()获取我的textView的屏幕截图并将其转换为UIImage。

class BackgroundEditTextViewController: UIViewController, UIPageViewControllerDataSource {

        @IBAction func instagramButton(sender: AnyObject) {
        println("yolo")

        EditTextViewController().imageForTextView(EditTextViewController().self.textView)
//        var editTextViewController = EditTextViewController()
//        editTextViewController.imageForTextView(editTextViewController.textView)
    }

}

BackgroundEditTextViewController类是我试图调用" imageForTextView()"的地方。当我点击" instagramButton"调用" imageForTextView()"我想在控制台中看到UIImage打印出来。但我一直收到这个错误fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)我试过制作" imageForTextView()"一个类功能但无济于事。

旁注:我在textView后面有一个UIImage,我希望将其包含在图片截图中,不太清楚如何修改我的imageForTextView()来截取textView& contentImageView。提前致谢。

2 个答案:

答案 0 :(得分:1)

简单(而不是面向对象)的方式是与世界共享imageForTextView,这意味着在该行的func之前添加public - 它是一个简单的解决方案,但它会告诉你你的函数是否正常工作

public func imageForTextView(UIView) -> UIImage

另一种方法是使用一个委托来创建一个函数,该函数接收一个闭包作为符合imageForTextView签名的参数,如此

public func doSomeDelegate((UIView)->UIImage)

然后使用doSomeDelegate调用imageForTextView 这是一般的想法

你可以在官方快速指南中找到一个很好的解释 https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html

浏览到谈论代表团的部分

答案 1 :(得分:0)

根据您的层次结构,您应该使用自定义委托或使函数imageForTextView共享。

相关问题