blank result in resultController with UISearchController - swift2

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

Related

xcode 9 webview with side menu

I need a side menu with table view and in it I need to get names from json file with links, in menu it must show names from json file and when I tap name i must open the url in my web view.
Alsow I need instead of json file, json url example, please help me
here is the link to my project
https://ufile.io/7qpzq
import UIKit
class SideMenuVC: UITableViewController {
final let urlString = "http://www.mocky.io/v2/5a02ad1d330000292bf6efa0"
var nameArray = [String]()
var iconArray = [String]()
var URLArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
self.downloadJsonWithURL()
}
func downloadJsonWithURL() {
let url = NSURL(string: urlString)
URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
print(jsonObj!.value(forKey: "menuItems") as Any)
if let menuArray = jsonObj!.value(forKey: "menuItems") as? NSArray {
for menuItems in menuArray{
if let menuDict = menuItems as? NSDictionary {
if let name = menuDict.value(forKey: "name") {
self.nameArray.append(name as! String)
}
if let icon = menuDict.value(forKey: "icon") {
self.iconArray.append(name as! String)
}
if let url = menuDict.value(forKey: "url") {
self.URLArray.append(name as! String)
}
}
}
}
OperationQueue.main.addOperation({
self.tableView.reloadData()
})
}
}).resume()
}
func downloadJsonWithTask() {
let url = NSURL(string: urlString)
var downloadTask = URLRequest(url: (url as URL?)!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 20)
downloadTask.httpMethod = "GET"
URLSession.shared.dataTask(with: downloadTask, completionHandler: {(data, response, error) -> Void in
let jsonData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
print(jsonData as Any)
}).resume()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return nameArray.count
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
_ = nameArray[indexPath.row]
tableView.deselectRow(at: indexPath, animated: true)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "menu", for: indexPath)
let label = cell.viewWithTag(1000) as! UILabel
label.text = nameArray[indexPath.row]
return cell
}

swift collectionview in tableview load images horizontally in collectionview

I need horizontal images in collectionview, which is inside every tableview cell. The problem I am facing is tableview gets loaded easily, but collectionview doesn't get loaded before tableview cells, because tableview loads very quickly, and hence the array for collectionview gets changed.
The code I am using for the whole view, is -
import UIKit
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,NSURLConnectionDelegate {
#IBOutlet var tbl_data: UITableView!
var mutableData: NSMutableData!
var response: NSURLResponse!
var connection: NSURLConnection!
var thedata:NSArray!
var ary_OF_collectionView:NSArray!
override func viewDidLoad() {
super.viewDidLoad()
connection_GetPeopleList()
thedata = NSArray()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return thedata.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
//println("INdex===\(indexPath.row)")
let cell = tableView.dequeueReusableCellWithIdentifier("dTableViewCell", forIndexPath: indexPath) as! dTableViewCell
var c_snippet:String = ""
if let checkC_snip:AnyObject = thedata.objectAtIndex(indexPath.row).valueForKey("c_snippet")
{
c_snippet = checkC_snip as! String
}
var getImageArray:NSArray = (thedata.objectAtIndex(indexPath.row).valueForKey("images") as? NSArray)!
cell.lbl_like.text = c_snippet
cell.co_v.tag = indexPath.row
if(getImageArray.count > 0)
{
if(getImageArray.count == 1)
{
var getimagePath:String = getImageArray.objectAtIndex(0) as! String
if(!getimagePath.isEmpty)
{
ary_OF_collectionView = getImageArray
}else
{
ary_OF_collectionView = NSArray()
}
}else
{
ary_OF_collectionView = getImageArray
}
}else
{
ary_OF_collectionView = NSArray()
}
cell.co_v.dataSource = self
cell.co_v.delegate = self
cell.co_v.reloadData()
cell.selectionStyle = UITableViewCellSelectionStyle.None
return cell
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return ary_OF_collectionView.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as! CollectionViewCell
var getImageUrl:String! = ary_OF_collectionView.objectAtIndex(indexPath.row) as! String
println(getImageUrl)
// This is image loader From == https://github.com/natelyman/SwiftImageLoader
ImageLoader.sharedLoader.imageForUrl(getImageUrl, completionHandler:{(image: UIImage?, url: String) in
cell.img.image = image
})
//cell.img.image = UIImage(named: ) as UIImage!
return cell
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath)
{
println("INinininin===\(indexPath.row)")
// var cell:dTableViewCell = cell as! dTableViewCell
// [cell setCollectionViewDataSourceDelegate:self index:indexPath.row];
}
func scrollViewDidScroll(scrollView: UIScrollView) {
println(scrollView)
// println("INinininin===\(scrollView.tag)")
}
func connection_GetPeopleList()
{
let urlPath: String = "http://carbonchase.com/v1.1/get_jives.php?user_id=3221128362&at=0&newsfeeds&count=10"
println("get_People List == \(urlPath)")
var escapedAddress = urlPath.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
var url: NSURL = NSURL(string: escapedAddress!)!
var request1: NSURLRequest = NSURLRequest(URL: url)
self.connection = NSURLConnection(request: request1, delegate: self, startImmediately: true);
connection.start()
}
func connection(connection: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
self.response = response
self.mutableData = NSMutableData()
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
self.mutableData.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection!)
{
if let jsonResult: NSArray = NSJSONSerialization.JSONObjectWithData(self.mutableData, options: nil, error:nil) as? NSArray {
thedata = jsonResult
self.tbl_data.reloadData();
self.tbl_data.delegate=self;
self.tbl_data.dataSource=self;
}
}
func connection(connection: NSURLConnection, didFailWithError error: NSError) {
println("\(error)")
}
}// END
EDITED
CollectionView is not working

How to make collectionView stop blinking

I have a problem with my collection view, which gives me a 'blink' a second after the view gets appeared on the screen.
Could it be the viewDidLoad or the viewDidAppear that causes this?
This is my current Swift code:
class HomeViewController: UIViewController
{
// MARK: IBOutlets
#IBOutlet weak var backgroundImageView: UIImageView!
#IBOutlet weak var collectionView: UICollectionView!
#IBOutlet weak var currentUserProfileImageButton: UIButton!
#IBOutlet weak var currentUserFullNameButton: UIButton!
// MARK: - UICollectionViewDataSource
private var interests = [Interest]()
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if PFUser.currentUser() == nil {
// the user hasn't logged in yet
showLogin()
} else {
// the user logged in, do something else
fetchInterests()
let center = NSNotificationCenter.defaultCenter()
let queue = NSOperationQueue.mainQueue()
center.addObserverForName("NewInterestCreated", object: nil, queue: queue, usingBlock: { (notification) -> Void in
if let newInterest = notification.userInfo?["newInterestObject"] as? Interest {
if !self.interestWasDisplayed(newInterest) {
self.interests.insert(newInterest, atIndex: 0)
self.collectionView.reloadData()
}
}
})
}
}
func interestWasDisplayed(newInterest: Interest) -> Bool {
for interest in interests {
if interest.objectId! == newInterest.objectId! {
return true
}
}
return false
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if UIScreen.mainScreen().bounds.size.height == 480.0 {
let flowLayout = self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout
flowLayout.itemSize = CGSizeMake(250.0, 300.0)
}
configureUserProfile()
}
func configureUserProfile()
{
// configure image button
currentUserProfileImageButton.contentMode = UIViewContentMode.ScaleAspectFill
currentUserProfileImageButton.layer.cornerRadius = currentUserProfileImageButton.bounds.width / 2
currentUserProfileImageButton.layer.masksToBounds = true
}
private struct Storyboard {
static let CellIdentifier = "Interest Cell"
}
#IBAction func userProfileButtonClicked()
{
PFUser.logOut()
showLogin()
}
// MARK: - Fetch Data From Parse
func fetchInterests()
{
let currentUser = User.currentUser()!
let interestIds = currentUser.interestIds
if interestIds?.count > 0
{
let interestQuery = PFQuery(className: Interest.parseClassName())
interestQuery.orderByDescending("updatedAt")
interestQuery.cachePolicy = PFCachePolicy.NetworkElseCache
interestQuery.whereKey("objectId", containedIn: interestIds)
interestQuery.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if error == nil {
if let interestObjects = objects as [PFObject]? {
self.interests.removeAll()
for interestObject in interestObjects {
let interest = interestObject as! Interest
self.interests.append(interest)
}
self.collectionView.reloadData()
}
} else {
print("\(error!.localizedDescription)")
}
})
}
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "Show Interest" {
let cell = sender as! InterestCollectionViewCell
let interest = cell.interest
let navigationViewController = segue.destinationViewController as! UINavigationController
let interestViewController = navigationViewController.topViewController as! InterestViewController
interestViewController.interest = interest
} else if segue.identifier == "CreateNewInterest" {
_ = segue.destinationViewController as! NewInterestViewController
} else if segue.identifier == "Show Discover" {
_ = segue.destinationViewController as! DiscoverViewController
}
}
func showLogin()
{
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let welcomeNavigationVC = storyboard.instantiateViewControllerWithIdentifier("WelcomeNavigationViewController") as! UINavigationController
self.presentViewController(welcomeNavigationVC, animated: true, completion: nil)
}
}
extension HomeViewController : UICollectionViewDataSource{
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int
{
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return interests.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(Storyboard.CellIdentifier, forIndexPath: indexPath) as! InterestCollectionViewCell
cell.interest = self.interests[indexPath.item]
return cell
}
}
extension HomeViewController : UIScrollViewDelegate{
func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>)
{
let layout = self.collectionView?.collectionViewLayout as! UICollectionViewFlowLayout
let cellWidthIncludingSpacing = layout.itemSize.width + layout.minimumLineSpacing
var offset = targetContentOffset.memory
let index = (offset.x + scrollView.contentInset.left) / cellWidthIncludingSpacing
let roundedIndex = round(index)
offset = CGPoint(x: roundedIndex * cellWidthIncludingSpacing - scrollView.contentInset.left, y: -scrollView.contentInset.top)
targetContentOffset.memory = offset
}
}
extension HomeViewController : PFLogInViewControllerDelegate, PFSignUpViewControllerDelegate{
func presentLoginViewController()
{
let logInController = PFLogInViewController()
let signupController = PFSignUpViewController()
signupController.delegate = self
logInController.delegate = self
logInController.fields = [PFLogInFields.UsernameAndPassword, PFLogInFields.LogInButton, PFLogInFields.SignUpButton]
logInController.signUpController = signupController
presentViewController(logInController, animated: true, completion: nil)
}
func logInViewController(logInController: PFLogInViewController, didLogInUser user: PFUser)
{
logInController.dismissViewControllerAnimated(true, completion: nil)
}
func signUpViewController(signUpController: PFSignUpViewController, didSignUpUser user: PFUser)
{
signUpController.dismissViewControllerAnimated(true, completion: nil)
}
}
Thanks guys :)

Terminator found in the middle of a basic block

All went fine until my project won't compile.I see those things on two of my files.
Terminator found in the middle of a basic block!
label %50
LLVM ERROR: Broken function found, compilation aborted!
Terminator found in the middle of a basic block!
label %71
LLVM ERROR: Broken function found, compilation aborted!
And the error the compiler give
Command /Applications/Xcode-beta 2.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1
I tried solving it, but no success.
Older version of the files compile.
The problem is in the files,but what is the terminator?
Where is the problem?
EDIT
Here is some code, the classes are big
LandscapeViewController
import UIKit
class LandscapeViewController: UIViewController,UIScrollViewDelegate {
// MARK: Properties
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var pageControl: UIPageControl!
var search: Search!
private var firstTime = true
private var downloadTasks = [NSURLSessionDownloadTask]()
#IBAction func pageChange(sender: UIPageControl){
UIView.animateWithDuration(0.3, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
self.scrollView.contentOffset = CGPoint(x: self.scrollView.bounds.size.width * CGFloat(sender.currentPage), y: 0)
}, completion: nil )
}
// MARK: Buttons
private func tileButtons(searchResults: [SearchResult]){
var columnsPerPage = 5
var rowsPerPage = 3
var itemWidth: CGFloat = 96
var itemHeight: CGFloat = 88
var marginX: CGFloat = 0
var marginY: CGFloat = 20
let buttonWidth: CGFloat = 82
let buttonHeight: CGFloat = 82
let scrollViewWidth = scrollView.bounds.size.width
switch scrollViewWidth{
case 568:
columnsPerPage = 6
itemWidth = 94
marginX = 2
case 667:
columnsPerPage = 7
itemWidth = 95
itemHeight = 98
marginX = 1
marginY = 29
case 736:
columnsPerPage = 8
rowsPerPage = 4
itemWidth = 92
default:
break
}
let paddingHorz = (itemWidth - buttonWidth)/2
let paddingVert = (itemHeight - buttonHeight)/2
var row = 0
var column = 0
var x = marginX
for (index,searchResult) in searchResults.enumerate(){
let button = UIButton(type: .Custom)
button.setBackgroundImage(UIImage(named: "LandscapeButton"), forState: .Normal)
downloadImageForSearchResult(searchResult, andPlaceOnButton: button)
button.tag = 2000 + index
button.addTarget(self, action: Selector("buttonPressed:"), forControlEvents: .TouchUpInside)
button.backgroundColor = UIColor.whiteColor()
button.frame = CGRect(x: x + paddingHorz, y: marginY + CGFloat(row)*itemHeight + paddingVert, width: buttonWidth, height: buttonHeight)
scrollView.addSubview(button)
++row
if row == rowsPerPage{
row = 0
++column
x += itemWidth
if column == columnsPerPage{
column = 0
x += marginX * 2
}
}
}
let buttonsPerPage = columnsPerPage * rowsPerPage
let numPages = 1 + (searchResults.count - 1) / buttonsPerPage
pageControl.numberOfPages = numPages
pageControl.currentPage = 0
scrollView.contentSize = CGSize(width: CGFloat(numPages) * scrollViewWidth, height: scrollView.bounds.size.height)
}
private func downloadImageForSearchResult(searchResult: SearchResult,andPlaceOnButton button: UIButton){
if let url = NSURL(string: searchResult.artworkURL60){
let session = NSURLSession.sharedSession()
let downloadTask = session.downloadTaskWithURL(url,completionHandler: { [weak button] url, response, error in
if error == nil && url != nil{
if let data = NSData(contentsOfURL: url!){
if let image = UIImage(data: data){
let resizedImage = image.resizedImageWithBounds(CGSize(width: 60, height: 60))
dispatch_async(dispatch_get_main_queue()){
if let button = button{
button.setImage(resizedImage, forState: .Normal)
}
}
}
}
}
})
downloadTasks.append(downloadTask!)
downloadTask?.resume()
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ShowDetail"{
switch search.state{
case .Results(let list):
let destinationViewController = segue.destinationViewController as! DetailViewController
let searchResult = list[sender!.tag - 2000]
destinationViewController.searchResult = searchResult
default:
break
}
}
}
func buttonPressed(sender: UIButton){
performSegueWithIdentifier("ShowDetail", sender: sender)
}
// MARK: UIScrollViewDelegate
func scrollViewDidScroll(scrollView: UIScrollView) {
let width = scrollView.bounds.size.width
let currentPage = Int((scrollView.contentOffset.x + width/2) / width)
pageControl.currentPage = currentPage
}
// MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
pageControl.numberOfPages = 0
scrollView.backgroundColor = UIColor(patternImage: UIImage(named: "LandscapeBackground")!)
view.removeConstraints(view.constraints)
view.translatesAutoresizingMaskIntoConstraints = true
pageControl.removeConstraints(pageControl.constraints)
pageControl.translatesAutoresizingMaskIntoConstraints = true
scrollView.removeConstraints(scrollView.constraints)
scrollView.translatesAutoresizingMaskIntoConstraints = true
// Do any additional setup after loading the view.
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
scrollView.frame = view.bounds
pageControl.frame = CGRect(x: 0, y: view.frame.size.height - pageControl.frame.size.height, width: view.frame.size.width, height: pageControl.frame.size.height)
if firstTime{
firstTime = false
switch search.state{
case .NotSearchedYet:
break
case .Loading:
showSpinner()
case .NoResults:
showNothingFoundLabel()
case.Results(let list):
tileButtons(list)
}
}
}
private func showNothingFoundLabel() {
let label = UILabel(frame: CGRect.zeroRect)
label.text = "Nothing Found"
label.backgroundColor = UIColor.clearColor()
label.textColor = UIColor.whiteColor()
label.sizeToFit()
var rect = label.frame
rect.size.width = ceil(rect.size.width/2) * 2
rect.size.height = ceil(rect.size.height/2) * 2
label.frame = rect
label.center = CGPoint(x: CGRectGetMidX(scrollView.bounds), y: CGRectGetMidY(scrollView.bounds))
view.addSubview(label)
}
private func showSpinner(){
let spinner = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge)
spinner.center = CGPoint(x: CGRectGetMidX(scrollView.bounds) + 0.5, y: CGRectGetMidY(scrollView.bounds) + 0.5)
spinner.tag = 1000
view.addSubview(spinner)
spinner.startAnimating()
}
func searchResultsRecived(){
hideSpinner()
switch search.state {
case .NotSearchedYet, .Loading:
break
case .NoResults:
showNothingFoundLabel()
case .Results(let list):
tileButtons(list)
}
}
private func hideSpinner(){
view.viewWithTag(1000)?.removeFromSuperview()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit{
print("deinit \(self)")
for task in downloadTasks{
task.cancel()
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
SearchViewController
import UIKit
class SearchViewController: UIViewController,UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate {
private struct TableViewCellIdentifier {
static let searchResultCell = "SearchResultCell"
static let nothingFoundCell = "NothingFoundCell"
static let loadingCell = "LoadingCell"
}
// MARK: LandscapeViewController
override func willTransitionToTraitCollection(newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.willTransitionToTraitCollection(newCollection, withTransitionCoordinator: coordinator)
switch newCollection.verticalSizeClass{
case .Compact:
showLandscapeViewWithCoordinator(coordinator)
case .Regular,.Unspecified:
hideLandscapeViewWithCoordinator(coordinator)
}
}
private func showLandscapeViewWithCoordinator(coordinator: UIViewControllerTransitionCoordinator){
precondition(landscapeViewController == nil)
landscapeViewController = storyboard?.instantiateViewControllerWithIdentifier("LandscapeViewController") as? LandscapeViewController
if let controller = landscapeViewController{
controller.search = search
controller.view.frame = view.frame
controller.view.alpha = 0
view.addSubview(controller.view)
addChildViewController(controller)
coordinator.animateAlongsideTransition({ _ in
if self.presentedViewController != nil{
self.dismissViewControllerAnimated(true, completion: nil)
}
self.searchBar.resignFirstResponder()
controller.view.alpha = 1
}, completion: { _ in
controller.didMoveToParentViewController(self)
})
}
}
private func hideLandscapeViewWithCoordinator(coordinator: UIViewControllerTransitionCoordinator){
if let controller = landscapeViewController{
controller.willMoveToParentViewController(nil)
coordinator.animateAlongsideTransition({ _ in
controller.view.alpha = 0
}, completion: { _ in
if self.presentedViewController != nil {
self.dismissViewControllerAnimated(true, completion: nil)
}
controller.view.removeFromSuperview()
controller.removeFromParentViewController()
self.landscapeViewController = nil
})
}
}
private func showNetworkError(){
let alert = UIAlertController(title: "Whoops...", message: "There was an error reading from the iTunes Store. Please try again.", preferredStyle: .Alert)
let action = UIAlertAction(title: "OK", style: .Default, handler: nil)
alert.addAction(action)
presentViewController(alert, animated: true, completion: nil)
}
// MARK: Detail ViewController
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ShowDetail" {
switch search.state{
case . Results(let list):
let indexPath = sender as! NSIndexPath
let searchResult = list[indexPath.row]
let detailViewController = segue.destinationViewController as! DetailViewController
detailViewController.searchResult = searchResult
default:
break
}
}
}
// MARK: Properties
#IBOutlet weak var searchBar: UISearchBar!
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var segmentedControl: UISegmentedControl!
let search = Search()
private var landscapeViewController: LandscapeViewController?
// MARK: Methodes
#IBAction func segmentedControl(sender: UISegmentedControl) {
performSearch()
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.contentInset = UIEdgeInsets(top: 108, left: 0, bottom: 0, right: 0)
tableView.rowHeight = 80
searchBar.becomeFirstResponder()
configureNib(nibName: TableViewCellIdentifier.searchResultCell)
configureNib(nibName: TableViewCellIdentifier.nothingFoundCell)
configureNib(nibName: TableViewCellIdentifier.loadingCell)
}
private func configureNib(nibName nibName: String){
let cellNib = UINib(nibName: nibName, bundle: nil)
tableView.registerNib(cellNib, forCellReuseIdentifier: nibName)
}
// MARK: UISearchBarDelegate
func searchBarSearchButtonClicked(searchBar: UISearchBar){
performSearch()
}
private func performSearch() {
if let category = Search.Category(rawValue: segmentedControl.selectedSegmentIndex){
search.performSearchForText(searchBar.text!, category: category){
success in
if !success{
self.showNetworkError()
}
if let controller = self.landscapeViewController{
controller.searchResultsRecived()
}
self.tableView.reloadData()
}
tableView.reloadData()
searchBar.resignFirstResponder()
}
}
func positionForBar(bar: UIBarPositioning) -> UIBarPosition {
return .TopAttached
}
// MARK: TableView
// MARK: - UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch search.state{
case .NotSearchedYet:
return 0
case .Loading,.NoResults:
return 1
case .Results(let list):
return list.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
switch search.state{
case .NotSearchedYet:
fatalError("Should never get here")
case .Loading:
let cell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifier.loadingCell, forIndexPath: indexPath)
let spinner = cell.viewWithTag(100) as! UIActivityIndicatorView
spinner.startAnimating()
return cell
case .NoResults:
return tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifier.nothingFoundCell, forIndexPath: indexPath)
case .Results(let list):
let cell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifier.searchResultCell, forIndexPath: indexPath) as! SearchResultCell
let searchResult = list[indexPath.row]
cell.configureForSearchResult(searchResult)
return cell
}
}
// MARK: UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
performSegueWithIdentifier("ShowDetail", sender: indexPath)
}
func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
switch search.state{
case .NotSearchedYet,.NoResults,.Loading:
return nil
case .Results:
return indexPath
}
}
}
This is a bug in the Swift compiler, you'll want to file a radar with Apple to report this. There's nothing you can do about it otherwise.
I had this error because I had a switch of an enum with a case that contain an Array payload (don't ask me why, I don't know).
I think the enum is the search state inside the tableView:cellForRowAtIndexPath: method of SearchViewController and the prepareForSegue: method of LandscapeViewController (the .Result case contain a list).
In my case, changing the payload to a Set instead of an Array worked. (as a workaroud until it's fixed)

How can I add a top margin to my tableview in Xcode?

I'm trying to add an image on the very top of the first cell of a table view. How can i make the table view have a top margin? Right now, the image is just overlapping the tableview. I am trying to just get the table view to come down a little bit. I do not want to make it smaller or something like that. I just want to add a button to the top of the tableview.
//
// usersVC.swift
// CaastRun
//
// Created by Computer on 5/23/15.
// Copyright (c) 2015 Caast. All rights reserved.
//
import UIKit
class usersVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var resultsTable: UITableView!
var resultsNameArray = [String]()
var resultsUserNameArray = [String]()
var resultsImageFiles = [PFFile]()
override func viewDidLoad() {
super.viewDidLoad()
let theWidth = view.frame.size.width
let theHeight = view.frame.size.height
resultsTable.frame = CGRectMake(0, 0, theWidth, theHeight)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
resultsNameArray.removeAll(keepCapacity: false)
resultsUserNameArray.removeAll(keepCapacity: false)
resultsImageFiles.removeAll(keepCapacity: false)
var query = PFUser.query()
query!.whereKey("username", notEqualTo: PFUser.currentUser()!.username!)
query!.findObjectsInBackgroundWithBlock {
(objects:[AnyObject]?, error:NSError?) -> Void in
if error == nil {
for object in objects! {
self.resultsNameArray.append(object.objectForKey("profileName") as! String)
self.resultsImageFiles.append(object.objectForKey("photo") as! PFFile)
self.resultsUserNameArray.append(object.objectForKey("username") as! String)
self.resultsTable.reloadData()
}
}
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return resultsNameArray.count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 64
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:usersCell = tableView.dequeueReusableCellWithIdentifier("Cell") as! usersCell
cell.profileLbl.text = self.resultsNameArray[indexPath.row]
cell.usernameLbl.text = self.resultsUserNameArray[indexPath.row]
var query = PFQuery(className: "follow")
query.whereKey("user", equalTo: PFUser.currentUser()!.username!)
query.whereKey("userToFollow", equalTo: cell.usernameLbl.text!)
query.countObjectsInBackgroundWithBlock {
(count:Int32, error:NSError?) -> Void in
if error == nil {
if count == 0 {
cell.followBtn.setTitle("Follow", forState: UIControlState.Normal)
} else {
cell.followBtn.setTitle("Following", forState: UIControlState.Normal)
}
}
}
self.resultsImageFiles[indexPath.row].getDataInBackgroundWithBlock {
(imageData:NSData?, error:NSError?) -> Void in
if error == nil {
let image = UIImage(data: imageData!)
cell.imgView.image = image
}
}
return cell
}
#IBOutlet weak var searchText: UITextField!
#IBAction func searchButton(sender: AnyObject) {
resultsNameArray.removeAll(keepCapacity: false)
resultsUserNameArray.removeAll(keepCapacity: false)
resultsImageFiles.removeAll(keepCapacity: false)
var query = PFUser.query()
query!.whereKey("username", notEqualTo: PFUser.currentUser()!.username!)
query!.whereKey("profileName", containsString: self.searchText.text)
query!.findObjectsInBackgroundWithBlock {
(objects:[AnyObject]?, error:NSError?) -> Void in
if error == nil {
for object in objects! {
self.resultsNameArray.append(object.objectForKey("profileName") as! String)
self.resultsImageFiles.append(object.objectForKey("photo") as! PFFile)
self.resultsUserNameArray.append(object.objectForKey("username") as! String)
self.resultsTable.reloadData()
}
}
}
}
}
I am not sure if I understand your question, if you are trying to have a margin between your table and the view try this:
Swift 3
self.tableView.contentInset = UIEdgeInsets(top: 20,left: 0,bottom: 0,right: 0)
Swift 2
self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0);

Resources