swift - "0"无法快速转换为BackgroundView

标签 swift methods ios8.1 class-method

我有这个类方法,并且我在 View Controller 中调用这个方法

class func initWithNewFrame(var frame : CGRect?)
    {
        if let newFrame = frame
        {
            var backgroundView : BackgroundView = BackgroundView(frame: newFrame)

        }
    }

我正在打电话

var frameNew : CGRect = CGRectMake(self.view.frame.origin.x,
            self.view.frame.origin.y,
            self.view.frame.size.width,
            self.view.frame.size.height)
        self.gradientView = BackgroundView.initWithNewFrame(frameNew)

我收到此错误“0”无法快速转换为BackgroundView , 请解决这个问题并提前致谢。

最佳答案

原因:

错误来自这里:self.gradientView = BackgroundView.initWithNewFrame(frameNew)

您为 self.gradientView 分配了返回值 initWithNewFrame,但在您的代码中,initWithNewFrame 没有返回值。

在 Swift 中,无返回值意味着返回一个空元组。所以你得到了““0”不能转换为BackgroundView”错误,因为你想分配一个带有空元组的BackgroundView

也许这是您期望的方法:

class func initWithNewFrame(var frame : CGRect?) -> BackgroundView? 
    {
        var backgroundView : BackgroundView? = nil
        if let newFrame = frame
        {
            backgroundView = BackgroundView(frame: newFrame)

        }
        return backgroundView
    }

更新:

如果您想为 BackgroundView 类创建自定义初始值设定项,请尝试以下操作:

convenience init(var frame : CGRect?) {
    if let newFrame = frame
    {
        self.init(newFrame )
    }
    // Do custom thing
}

关于swift - "0"无法快速转换为BackgroundView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30045121/

相关文章:

ios - pod update --verbose & pod install --verbose 未完成,挂起

swift - Firestore 第一次查询

python - Python 中的多态性

c++ - VSC++,地址错误的虚拟方法,奇怪的错误

ios - 我怎样才能得到联系ID

ios - 是否可以使用相同的 View Controller 为每个 View Controller 显示不同的内容?

ios - UITableView 滚动到底部时更新数据

android - Android webview的loadData和loadDataWithBaseURL有什么区别

UITableView 快速获取 titleForHeadersInSection

ios - 使用未合并到我的应用程序中的数据文件