2016-08-13 488 views
1

在我的代碼我得到:缺少呼籲參數「編碼器」的說法斯威夫特

呼叫迅速

缺少參數「編碼」的說法我是一個初學者斯威夫特我已經嘗試過所有的事情,包括研究這個問題,但沒有找到答案。謝謝。

我得到這個錯誤代碼是:

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

好的,我更新了問題。 –

回答

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

3

該錯誤提示編譯器有問題搞清楚哪些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