“ViewController”类没有初始化错误:xcode Beta 4
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24899681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Class 'ViewController' has no initializers error: xcode Beta 4
提问by bevbomb
I'm receiving this error on a file which works previously on all other beta's, for some reason in the beta 4 xcode it displays this error, its the only file in the entire project which does it and i'm not sure why its doing it just for beta 4, any ideas? i've tried using the default init on it but i get a compile error.
我在以前在所有其他测试版上运行的文件上收到此错误,出于某种原因,在测试版 4 xcode 中它显示此错误,它是整个项目中唯一执行此错误的文件,我不知道为什么这样做它仅适用于测试版 4,有什么想法吗?我试过在它上面使用默认的 init 但我得到一个编译错误。
i think theres too much code to place in, so instead heres the file direct.
我认为要放入的代码太多,所以直接将文件改为继承人。
https://www.dropbox.com/s/7a6q1oyj2qnshu0/SearchView.swift
https://www.dropbox.com/s/7a6q1oyj2qnshu0/SearchView.swift
import UIKit
import CloudKit
import Foundation
import QuartzCore
import MediaPlayer
import AVFoundation
import CoreMedia
class SearchViewController: UIViewController, UITableViewDelegate,UITableViewDataSource, UISearchBarDelegate, UIScrollViewDelegate, SearchAPIProtocol {
enum UIUserInterfaceIdiom : Int {
case Unspecified
case Phone // iPhone and iPod touch style UI
case Pad // iPad style UI
}
var searchCell: SearchViewCell = SearchViewCell()
var progressView: CGCircleProgressView = CGCircleProgressView()
var tableData = NSArray()
var buttonIndex: NSIndexPath?
var previousIndex: NSIndexPath?
var songPlayer = AVPlayer()
var hidden = Bool()
var startContentOffset = CGFloat()
var lastContentOffset = CGFloat()
var firstAmount = Int()
var imageCache = NSMutableDictionary()
var searchOpen: Bool?
var searchAPI: SearchAPIController = SearchAPIController()
@IBOutlet var tableView: UITableView!
@IBOutlet var searchBar: UISearchBar!
@IBOutlet var sBar: UIView!
override func viewDidLoad() {
super.viewDidLoad()
var nib = UINib(nibName: "SearchViewCell", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "Cell")
searchAPI.delegate = self
searchAPI.searchItunesFor("Justin")
// container = CKContainer.defaultContainer()
//publicDatabase = container?.privateCloudDatabase
self.setUpSearchBar()
hidden = false
self.tableView.contentInset = UIEdgeInsetsMake(108, 0, 0, 0)
var subViews: UIView = searchBar.subviews.bridgeToObjectiveC().lastObject as UIView
var textView: UITextField = subViews.subviews.bridgeToObjectiveC().objectAtIndex(1) as UITextField
textView.textColor = UIColor.whiteColor()
// Do any additional setup after loading the view, typically from a nib.
}
func setUpSearchBar() {
var visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Dark)) as UIVisualEffectView
visualEffectView.frame = sBar.bounds
sBar.addSubview(visualEffectView)
sBar.sendSubviewToBack(visualEffectView)
sBar.addConstraint(NSLayoutConstraint(
item:visualEffectView, attribute:.CenterX,
relatedBy:.Equal, toItem:sBar,
attribute:.CenterX, multiplier:1, constant:0))
sBar.addConstraint(NSLayoutConstraint(
item:visualEffectView, attribute:.CenterY,
relatedBy:.Equal, toItem:sBar,
attribute:.CenterY, multiplier:1, constant:0))
sBar.addConstraint(NSLayoutConstraint(
item:visualEffectView, attribute:.Width,
relatedBy:.Equal, toItem:sBar,
attribute:.Width, multiplier:1, constant:0))
sBar.addConstraint(NSLayoutConstraint(
item:visualEffectView, attribute:.Height,
relatedBy:.Equal, toItem:sBar,
attribute:.Height, multiplier:1, constant:0))
sBar.addConstraint(NSLayoutConstraint(
item:visualEffectView, attribute:.Leading,
relatedBy:.Equal, toItem:sBar,
attribute:.Leading, multiplier:1, constant:0))
sBar.addConstraint(NSLayoutConstraint(
item:visualEffectView, attribute:.Trailing,
relatedBy:.Equal, toItem:sBar,
attribute:.Trailing, multiplier:1, constant:0))
visualEffectView.setTranslatesAutoresizingMaskIntoConstraints(false)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
and displaying tableview:
并显示tableview:
func tableView(tableView: UITableView!, heightForHeaderInSection section: Int) -> Int {
return 1
}
func tableView(tableView: UITableView!, viewForFooterInSection section: Int) -> UIView {
var view = UIView(frame: CGRect.zeroRect)
return view
}
func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
return 81
}
func tableView(tableView: UITableView!, heightForFootInSection section: Int) -> Int {
return 1
}
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
if self.tableData.count > firstAmount {
return firstAmount + 1
} else {
return 0
}
//return self.tableData!.count
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let CellIndentifier: NSString = "Cell"
let moreID: String = "moreCell"
var searchCell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as SearchViewCell
var rowData: NSDictionary = self.tableData[indexPath!.row] as NSDictionary
var rows = indexPath.row
if rows == firstAmount {
searchCell.loadMoreView.hidden = false
} else {
searchCell.selectionStyle = UITableViewCellSelectionStyle.None
searchCell.clipsToBounds = true
searchCell.loadMoreView.hidden = true
var artistName = rowData["artistName"] as String
var trackName = rowData["trackName"] as String
var previewURL = rowData["previewUrl"] as String
//var artistURL = rowData["artistViewUrl"] as String
//var buyURL = rowData["trackViewUrl"] as String
var artworkURL = rowData["artworkUrl100"] as String
searchCell.previewButton.addTarget(self, action: "flipButton:", forControlEvents: UIControlEvents.TouchUpInside)
searchCell.songName.text = trackName
searchCell.artistName.text = artistName
var layer: CALayer = searchCell.blurView.layer
layer.shadowOffset = CGSizeMake(0, 0)
layer.shadowColor = UIColor(white: 0.0, alpha: 1.0).CGColor
layer.shadowRadius = 1.0
layer.shadowOpacity = 0.5
searchCell.backImage.clipsToBounds = true
var visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Dark)) as UIVisualEffectView
visualEffectView.frame = searchCell.blurView.bounds
searchCell.blurView.addSubview(visualEffectView)
searchCell.blurView.sendSubviewToBack(visualEffectView)
// NSLayoutConstraint.deactivateConstraints(searchCell.blurView.constraints())
searchCell.blurView.addConstraint(NSLayoutConstraint(
item:visualEffectView, attribute:.CenterX,
relatedBy:.Equal, toItem:searchCell.blurView,
attribute:.CenterX, multiplier:1, constant:0))
searchCell.blurView.addConstraint(NSLayoutConstraint(
item:visualEffectView, attribute:.CenterY,
relatedBy:.Equal, toItem:searchCell.blurView,
attribute:.CenterY, multiplier:1, constant:0))
searchCell.blurView.addConstraint(NSLayoutConstraint(
item:visualEffectView, attribute:.Width,
relatedBy:.Equal, toItem:searchCell.blurView,
attribute:.Width, multiplier:1, constant:0))
searchCell.blurView.addConstraint(NSLayoutConstraint(
item:visualEffectView, attribute:.Height,
relatedBy:.Equal, toItem:searchCell.blurView,
attribute:.Height, multiplier:1, constant:0))
searchCell.blurView.addConstraint(NSLayoutConstraint(
item:visualEffectView, attribute:.Leading,
relatedBy:.Equal, toItem:searchCell.blurView,
attribute:.Leading, multiplier:1, constant:0))
searchCell.blurView.addConstraint(NSLayoutConstraint(
item:visualEffectView, attribute:.Trailing,
relatedBy:.Equal, toItem:searchCell.blurView,
attribute:.Trailing, multiplier:1, constant:0))
visualEffectView.setTranslatesAutoresizingMaskIntoConstraints(false)
var placeHolder = UIImage(named: "placeHolder.png")
searchCell.artworkIMG.image = placeHolder
searchCell.backImage.image = placeHolder
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
var urlString: NSString = rowData["artworkUrl100"] as NSString
var image: UIImage? = self.imageCache.valueForKey(urlString) as? UIImage
if( !image? ) {
var imgURL: NSURL = NSURL(string: urlString)
var request: NSURLRequest = NSURLRequest(URL: imgURL)
var urlConnection: NSURLConnection = NSURLConnection(request: request, delegate: self)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
if !error? {
image = UIImage(data: data)
self.imageCache.setValue(image, forKey: urlString)
searchCell.artworkIMG.image = image
searchCell.backImage.image = image
} else {
println("Error: \(error.localizedDescription)")
}
})
} else {
searchCell.artworkIMG.image = image
searchCell.backImage.image = image
}
})
}
return searchCell
}
func tableView(tableView: UITableView!, willDisplayCell cell: UITableViewCell!, forRowAtIndexPath indexPath: NSIndexPath!) {
cell.layer.transform = CATransform3DMakeScale(0.1,0.1,1)
/*UIView.animateWithDuration(0.25, animations: {
cell.layer.transform = CATransform3DMakeScale(1,1,1)
})*/
UIView.animateWithDuration(0.4, animations: {
cell.layer.transform = CATransform3DMakeScale(1.1,1.1,1.1)
}, completion: {(value: Bool) in
cell.layer.transform = CATransform3DMakeScale(1,1,1)
})
}
回答by Swift Soda
From SwiftSoda.com:
来自 SwiftSoda.com:
Many Swift Programmers are having a little trouble with ViewControllers and Xcode beta 4. The error is viewController is not constructible with ().
许多 Swift 程序员在使用 ViewControllers 和 Xcode beta 4 时遇到了一些麻烦。错误是 viewController 不能用 () 构造。
But if you look at your View Controller, you will see another error, Class viewController has no initializers. Followed by (replace with whichever outlets you are using) NSTextField has non-optional type ‘NSTextField'.
但是如果你查看你的 View Controller,你会看到另一个错误,ViewController 类没有初始化器。其次是(替换为您使用的任何插座)NSTextField 具有非可选类型“NSTextField”。
Setting the IBOutlets with ? the end corrects the problem. After that you will need to change some syntax each time the Outlet's variable is used with !.
用 ? 设置 IBOutlets 最后纠正了问题。之后,每次将 Outlet 的变量与 ! 一起使用时,您都需要更改一些语法。
Here is a brief example:
下面是一个简单的例子:
//ViewController Class File:
// view controller swift file for OS X
import AppKit
// you can use () for AnyObject as long as you do some things first.
var mvc = vc()
class vc: NSViewController {
// the key here is "?" after NSTextField to declare an optional
@IBOutlet var myStatusField: NSTextField?
}
//AppDelegate File:
import AppKit
//here we load the view inside the AppDelegate
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet var window: NSWindow!
func applicationDidFinishLaunching(aNotification: NSNotification?) {
// Insert code here to initialize your application
//load and center view in main window
window.contentView.addSubview(mvc.view)
mvc.view.frame = window.contentView.bounds
//here we display some text in myStatusField with *!.stringValue
// ! is used to unwrap the optional.
mvc.myStatusField!.stringValue = "Swift Soda wishes you a good day!"
}
}
回答by Beninho85
Had the same error because one of my properties was not initialized. Hope it helps some peoples
有同样的错误,因为我的一个属性没有初始化。希望它可以帮助一些人
回答by xmkevinchen
I believe the easiest way is just override an init function without override keyword and just call super.init, and it works like this
我相信最简单的方法是在没有覆盖关键字的情况下覆盖 init 函数,然后调用 super.init,它的工作原理是这样的
@IBOutlet weak var tableView: UITableView!
init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
回答by Swift Soda
you may want to safely unwrap any optionals with an if IBOutletName Statement like this:
您可能希望使用 if IBOutletName 语句安全地解开任何可选项,如下所示:
if mvc.myStatusField {
mvc.myStatusField!.stringValue = "Swift Soda wishes you a good day!"
}
That way your app will not crash.
这样你的应用就不会崩溃。
I'm trying to get IBOutlets to work without using ? and ! (optionals), but so far it seems to be the only thing that works in beta4 with a NSViewController.
我试图让 IBOutlets 在不使用 ? 和 !(可选),但到目前为止它似乎是唯一可以在 beta4 中使用 NSViewController 的东西。
回答by pkc456
Implement the below in your view controller:
在您的视图控制器中实现以下内容:
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
回答by Ganesh Pawar
I got this error because I declared constant optional, you can see code below :
我收到这个错误是因为我声明了常量可选,你可以看到下面的代码:
let subCategory: String?
I changed form let
to var
and problem solved for me.
Using Xcode 10, Swift 4.2
我改变了形式let
,以var
和问题就解决了我。使用 Xcode 10、Swift 4.2