缺少呼吁参数“编码器”的说法斯威夫特

问题描述:

在我的代码我得到:缺少呼吁参数“编码器”的说法斯威夫特

呼叫迅速

缺少参数“编码”的说法我是一个初学者斯威夫特我已经尝试过所有的事情,包括研究这个问题,但没有找到答案。谢谢。

我得到这个错误代码是:

let button: UIButton = UIButton(frame: CGRect(origin: CGPoint(x: ChecklistViewController().view.frame.width/2 + 117, y: ChecklistViewController().view.frame.size.height - 70), size: CGSize(width: 50, height: 50)))

+3

您应该编辑问题以分享产生此错误的代码行。 – Rob

+0

好的,我更新了问题。 –

我认为这个问题是您正在使用ChecklistViewController生成您的位置。 试试这个代码

let button: UIButton = UIButton(frame: CGRect(x: (CGRectGetMidX(self.view.frame) + 117) , y: (CGRectGetMaxY(self.view.frame) - 70) , size: CGSize(width: 50, height: 50))) 
+0

当我试图说我得到一个错误说:类型'NSObject - >() - > ChecklistViewController'的值没有成员'查看' –

+0

你是否在viewController中做到这一点?它需要位于一个班级内。 – Starlord

该错误提示编译器有问题搞清楚哪些init方法被调用,因此它是假设你的意思是叫init(coder:)

但让我们暂且搁置一秒钟。首先,让我们简化您的陈述以消除一些“噪音”。您可以使用CGRect(x:, y:, width:, height:),而不是使用CGRect(origin:, size:)。这将产生(在不同的线路分开它,使之更容易一些阅读):

let button = UIButton(frame: CGRect(
    x: ChecklistViewController().view.frame.width/2 + 117, 
    y: ChecklistViewController().view.frame.size.height - 70, 
    width: 50, 
    height: 50) 
) 

其次,这里的问题是,ChecklistViewController()语法实际上并没有引用现有ChecklistViewController。每当它看到ChecklistViewController()它正在创建该视图控制器的一个新实例(所以你可能有三个实例,原来的一个和你在这里意外创建的两个实例)。这当然不是你想要的。如果你在做这个,的视图控制器本身的实例方法之一,你只是参考self,如:

let button = UIButton(frame: CGRect(
    x: self.view.frame.width/2 + 117, 
    y: self.view.frame.size.height - 70, 
    width: 50, 
    height: 50) 
) 

一个更微妙的问题是,这个代码将只工作,如果的的frame已设置view。但是如果您在viewDidLoad中有此代码,则尚未设置frame。如果你在viewDidAppear中这样做,你可以避开这段代码。一般来说,您会使用自动布局来避免这种情况是这样的:

let button = UIButton() 
button.translatesAutoresizingMaskIntoConstraints = false 
// do additional configuration of the button here 

view.addSubview(button) 

NSLayoutConstraint.activateConstraints([ 
    button.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor, constant: 117), 
    button.centerYAnchor.constraintEqualToAnchor(view.centerYAnchor, constant: -70), 
    button.widthAnchor.constraintEqualToConstant(50), 
    button.heightAnchor.constraintEqualToConstant(50) 
]) 

因为我们这样做,支持自动布局,这意味着你可以在viewDidLoad做到这一点,如果你想要的。另外,这意味着如果旋转设备,约束将自动为您自动重新计算frame

说完所有这些之后,参数'编码器'缺少的参数可能是代码中其他问题的结果。但是,如果您修复了该按钮的声明,则可能能够更好地诊断代码中可能存在的其他任何问题。

+0

感谢您的帮助,但是当我在代码中使用“self”代替ChecklistViewController()时,我得到了一个不同的错误。这个错误说:类型'NSObject - >() - > ChecklistViewController'的值没有'view'的成员 –

+0

如果您是通过视图控制器的实例方法执行此操作,则只能使用'self'。这听起来不像是你这样做的地方,但没有更多的上下文,我们无法提供帮助。也就是说,你从哪里得到你问题的代码?但底线,不要使用'CheckViewController()'语法,而是获取对现有实例的引用。 – Rob