I keep getting this error: "could not find member row".
Here is my code:
import UIKit
import CoreData
class ListTableViewController: UITableViewController {
var myList: Array<AnyObject> = []
override func viewDidAppear(animated: Bool) {
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext!
let freq = NSFetchRequest(entityName: "List")
myList = context.executeFetchRequest(freq, error: nil)!
tableView.reloadData()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if segue.identifier == "update" {
//GETTING ERROR ON THIS NEXT LINE//
var selectedItem: NSManagedObject =
myList[self.tableView.indexPathForSelectedRow()?.row!] as! NSManagedObject
let IVC: ItemViewController =
segue.destinationViewController as! ItemViewController
IVC.item = selectedItem.valueForKey("item") as! String
IVC.quantity = selectedItem.valueForKey("quantity") as! String
IVC.info = selectedItem.valueForKey("info") as! String
IVC.existingItem = selectedItem
}
}
Can anyone please help me get rid of that error.
When you call self.tableView.indexPathForSelectedRow() you are getting back a NSIndexPath instance, not an integer. You then need to ask that NSIndexPath for its row. So the call should read self.tableView.indexPathForSelectedRow().row()
This is of course assuming you only have one section in your table view.
Try this:
var selectedItem = myList[self.tableView.indexPathForSelectedRow()!.row] as! NSManagedObject
Related
Here's my code do not suggest to remove IBAction I'm a beginner making a browser. I'm also
pretty new to this program:
import Cocoa
import WebKit
class ViewController: NSViewController, WKNavigationDelegate {
#IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
webView.navigationDelegate = self
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
}
}
#IBAction func didEnterKeyTapped( sender: NSTextField){
let urlString = sender.stringValue
guard let url = URL(string: urlString) else {return}
let urlRequest = URLRequest(url: url)
webView.load(urlRequest)
#IBAction func didnavigationButtonTapped ( sender: NSSegmentedControl){
if sender.selectedSegment == 0 {
webView.goBack()
}else {
webView.Forward()
}
}
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
let currentUrl = webView.url?.absoluteString ?? ""
guard let windowController = view.window?.windowController as? WindowController else {return}
let textField = windowController.urlTextField
textField?.stringValue = currentUrl
}
}
}
You declared the #IBActions outside of the ViewController class. An IBAction must be a member of a class. Move the IBActions inside the class to fix the compiler error.
Another problem in your code is you declared the didNavigationButtonTapped IBAction inside the didEnterKeyTapped IBAction. The two IBActions should be separate functions, such as the following:
#IBAction func didEnterKeyTapped( sender: NSTextField){
let urlString = sender.stringValue
guard let url = URL(string: urlString) else {return}
let urlRequest = URLRequest(url: url)
webView.load(urlRequest)
}
#IBAction func didnavigationButtonTapped ( sender: NSSegmentedControl) {
if sender.selectedSegment == 0 {
webView.goBack()
}else {
webView.Forward()
}
}
As a beginner in writing swift code, I am getting error in the following code:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = self.collectionView?.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CollectionViewCell
// Configure the cell
let imageURL = NSURL(string: usersImageArray[indexPath.row])
print("The image url is \(imageURL)")
let imageData = NSData(contentsOf: imageURL as! URL)
cell.userImage.image = UIImage(data: imageData as! Data)
cell.userName.text = usersNameArray[indexPath.row]
return cell
}
The imageURL does contain an image url and the imageData does contain image Data but still I get "fatal error: unexpectedly found nil while unwrapping an Optional value"
I have seen and read other questions and answers and tried but still I can not find the problem. What exactly is causing the error though it does contain the URL and image data?
UPDATED:
My CollectionViewCell Class:
import UIKit
class CollectionViewCell: UICollectionViewCell {
#IBOutlet weak var userImage: UIImageView!
#IBOutlet weak var userName: UILabel!
override func layoutSubviews() {
super.layoutSubviews()
self.makeImageRound()
}
func makeImageRound(){
self.userImage.layer.masksToBounds = true
self.userImage.layer.cornerRadius = self.userImage.frame.size.width/2.0
}
}
You have given the URL like this : optional(imageurl), it takes as it is , so you should avoid optional(. ) , to avoid this use '!' After userimagearray[indexpath.row]!
Try this and print imageurl and then see what happens
Try this
if imagedata == nil{
//give some image
}
else{
//give imagedata here
}
And take reuseidentifier = "cell"
Not cell whatever you take in a storyboard tableviewcell
i use 2 tableViewController with custom prototype in each (one for search, one for result)
I have in console (print...) the good result, but my custom cell are blanck
here is my code if someone could help
Ty
import UIKit
class search_TableViewController: UITableViewController, UISearchResultsUpdating {
#IBOutlet var sTableView: UITableView!
// Properties
// 1
var users:[[String:AnyObject]]!
var foundUsers:[[String:AnyObject]]!
// 2
var userDetails:[String:AnyObject]!
// 3
var resultController: UITableViewController!
var searchController: UISearchController!
override func viewDidLoad() {
super.viewDidLoad()
users = []
foundUsers = []
self.sTableView.dataSource = self
self.sTableView.delegate = self
self.automaticallyAdjustsScrollViewInsets = false
//ViewDidLoad
let storyboard = UIStoryboard(name: "Main", bundle: nil)
resultController = storyboard.instantiateViewControllerWithIdentifier("resultId") as! UITableViewController
resultController.tableView.delegate = self;
resultController.tableView.dataSource = self
resultController.tableView.delegate = self;
resultController.tableView.registerClass(result_TableViewCell.self, forCellReuseIdentifier: "resultPRTC")
// 3
searchController = UISearchController(searchResultsController: resultController)
searchController.hidesNavigationBarDuringPresentation = true
searchController.searchBar.searchBarStyle = .Minimal
searchController.searchResultsUpdater = self
self.sTableView.tableHeaderView = searchController.searchBar
// 4
self.definesPresentationContext = true
// 5
let session = NSURLSession.sharedSession()
let url:NSURL! = NSURL(string: "http://jsonplaceholder.typicode.com/users")
let task = session.downloadTaskWithURL(url) { (location: NSURL?, response: NSURLResponse?, error: NSError?) -> Void in
if (location != nil){
let data:NSData! = NSData(contentsOfURL: location!)
do{
self.users = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves) as! [[String : AnyObject]]
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.sTableView.reloadData()
})
}catch{
// Catch any exception
print("Something went wrong")
}
}else{
// Error
print("An error occurred \(error)")
}
}
// Start the download task
task.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: UISearchResultsUpdating
func updateSearchResultsForSearchController(searchController: UISearchController) {
foundUsers.removeAll()
for user in users{
let userName:String! = user["name"] as? String
if userName.localizedCaseInsensitiveContainsString(searchController.searchBar.text!) {
foundUsers.append(user)
print ("Liste 1 : \(foundUsers)")
self.resultController.tableView.reloadData()
}
}
}
//MARK: UITableViewDataSource
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//print (tableView)
if tableView == self.sTableView{
print ("userSearch :\(users.count)")
return users.count
}
//passe sur la recherche
print ("userResult:\(foundUsers.count)")
return foundUsers.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cellIdentifier: String!
var dic: [String:AnyObject]!
if tableView == self.sTableView{
cellIdentifier = "searchPRTC"
dic = self.users[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! search_TableViewCell
cell.sNom?.text = dic["name"] as? String
cell.sEmail?.text = dic["email"] as? String
return cell
}else{
cellIdentifier = "resultPRTC"
dic = self.foundUsers[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! result_TableViewCell
cell.rNom?.text = dic["name"] as? String
print ("Liste 2 : \(foundUsers)")
return cell
}
// let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath)
//cell.textLabel?.text = dic["name"] as? String
// cell.adresse?.text = dic["username"] as? String
}
}
If i use for result this code instead of my custom prototype i see the result - maybe this information could help a lot :
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath)
cell.textLabel?.text = dic["name"] as? String
i had it :
must delete this !
resultController.tableView.registerClass(result_TableViewCell.self, forCellReuseIdentifier: "resultPRTC")
Is someone know if it's possible to have only one view ? or i must have 2 tableview controller (one for search one for result)
ty
I am creating a page view application. I have written code for the ViewController:
import UIKit
class ViewController: UIViewController {
var pageViewController : UIPageViewController!
var pageTitles : NSArray!
var pageImages : NSArray!
#IBAction func restartAction(sender: AnyObject) {}
override func viewDidLoad() {
super.viewDidLoad()
self.pageTitles = NSArray(objects: "This Is Page One!", "This Is Page Two!")
self.pageImages = NSArray(objects: "page1", "page2")
self.pageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("PageViewController") as! UIPageViewController
self.pageViewController.dataSource = self // <–– Error
let startVC = self.viewControllerAtIndex(0) as ContentViewController
let viewControllers = NSArray(object: startVC)
self.pageViewController.setViewControllers(viewControllers as? [UIViewController], direction: .Forward, animated: true, completion: nil)
self.pageViewController.view.frame = CGRectMake(0, 30, self.view.frame.width, self.view.frame.height - 60)
self.addChildViewController(self.pageViewController)
self.view.addSubview(self.pageViewController.view)
self.pageViewController.didMoveToParentViewController(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func viewControllerAtIndex(index: Int) -> ContentViewController {
if ((self.pageTitles.count == 0) || (index >= self.pageTitles.count)) {
return ContentViewController()
}
let vc : ContentViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ContentViewController") as! ContentViewController
vc.imageFile = self.pageImages[index] as! String
vc.titleText = self.pageTitles[index] as! String
vc.pageIndex = index
return vc
}
func pageViewController(pageViewController: UIPageViewController, viewcontrollerBeforeViewController viewController: UIViewController) ->UIViewController? {
let vc = viewController as! ContentViewController
var index = vc.pageIndex as Int
if index == 0 || index == NSNotFound {
return nil
}
index--
return self.viewControllerAtIndex(index)
}
func pageViewController(pageViewController: UIPageViewController, viewcontrollerAfterViewController viewController: UIViewController) ->UIViewController? {
let vc = viewController as! ContentViewController
var index = vc.pageIndex as Int
if index == NSNotFound {
return nil
}
index++
if index == self.pageTitles.count {
return nil
}
return self.viewControllerAtIndex(index)
}
}
But I am getting an error on this line self.pageViewController.dataSource = self. The error is:
Cannot assign to property: 'self' is immutable
I am unsure of why self is immutable and how to fix it. If someone could please help, thanks in advance.
In swift you'll need to call self.pageViewController.setDelegate(self)
Delegates have been declared as methods, not properties in some cases
I think the compiler is not being very helpful here - try declaring the controller as following datasource protocol and see if that fixes this odd error
class ViewController: UIViewController, UIPageViewControllerDataSource { etc
func keyboardWillShow(notification:NSNotification){
let userInfo = notification.userInfo
let keyboardFrame = userInfo?[UIKeyboardFrameEndUserInfoKey] as NSValue
let keyboardSize = keyboardFrame.CGRectValue().size
let animationDurationValue = userInfo?[UIKeyboardAnimationDurationUserInfoKey] as NSValue
var animationDuration : NSTimeInterval = 0
animationDurationValue.getValue(&animationDuration)
self.keyboardDelegate?.keyboardWillShowWithSize(keyboardSize, andDuration: animationDuration)
}
In my program, I try to reposition my view when keyboard appears using the function above. With the same way of getting keyboard animation duration in my objective-c code. This one gives me the following status:
duration 5.18065378653631e-315
This is an abnormally small value. Where have I done wrong? Please help!
EDIT: For complete code:
import Foundation
import UIKit
#objc protocol LPKeyboardViewControllerDelegate {
func keyboardWillShowWithSize(size:CGSize, andDuration duration:NSTimeInterval)
func keyboardWillHideWithSize(size:CGSize,andDuration duration:NSTimeInterval)
}
/**
This view controller will move up its view when a keyboard appears in its view
*/
class LPKeyboardViewController: UIViewController {
var keyboardDelegate: LPKeyboardViewControllerDelegate?
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
println("Start listening to keyboard")
}
func keyboardWillShow(notification:NSNotification){
let userInfo = notification.userInfo
let keyboardFrame = userInfo?[UIKeyboardFrameEndUserInfoKey] as NSValue
let keyboardSize = keyboardFrame.CGRectValue().size
let animationDurationValue = userInfo?[UIKeyboardAnimationDurationUserInfoKey] as NSValue
var animationDuration : NSTimeInterval = 0
animationDurationValue.getValue(&animationDuration)
self.keyboardDelegate?.keyboardWillShowWithSize(keyboardSize, andDuration: animationDuration)
}
func keyboardWillHide(notification:NSNotification){
let userInfo = notification.userInfo
let keyboardFrame = userInfo?[UIKeyboardFrameEndUserInfoKey] as NSValue
let keyboardSize = keyboardFrame.CGRectValue().size
let animationDurationValue = userInfo?[UIKeyboardAnimationDurationUserInfoKey] as NSNumber
var animationDuration : NSTimeInterval = animationDurationValue.doubleValue
self.keyboardDelegate?.keyboardWillHideWithSize(keyboardSize, andDuration: animationDuration)
}
}
The docs state that the object for this key is an NSNumber so you don't have to jump through the hoops you are you can just do
let animationDurationValue = userInfo?[UIKeyboardAnimationDurationUserInfoKey] as NSNumber
let animationDuration = animationDurationValue.doubleValue