該錯誤提示編譯器有問題搞清楚哪些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
。
說完所有這些之後,參數'編碼器'缺少的參數可能是代碼中其他問題的結果。但是,如果您修復了該按鈕的聲明,則可能能夠更好地診斷代碼中可能存在的其他任何問題。
來源
2016-08-13 23:32:34
Rob
您應該編輯問題以分享產生此錯誤的代碼行。 – Rob
好的,我更新了問題。 –