I'm trying to send a request to search for movies, but when i tap on the search bar to write the text i get a crash in cellforrow and it's not calling numberofrows neither the request. Here's my code so far:
class InTheaters: UITableViewController, UISearchResultsUpdating, UISearchBarDelegate {
#IBOutlet weak var poster: UIImageView!
#IBOutlet weak var movieTitle: UILabel!
#IBOutlet weak var date: UILabel!
#IBOutlet weak var duration: UILabel!
#IBOutlet weak var rating: UILabel!
#IBOutlet var theatersTable: UITableView!
#IBOutlet weak var starsView: CosmosView!
var results = [Movie]()
var searchResults = [Search]()
var resultSearchController: UISearchController!
private let key = "qtqep7qydngcc7grk4r4hyd9"
override func viewDidLoad() {
super.viewDidLoad()
self.resultSearchController = UISearchController(searchResultsController: nil)
self.resultSearchController.searchResultsUpdater = self
self.resultSearchController.dimsBackgroundDuringPresentation = false
self.resultSearchController.searchBar.sizeToFit()
self.resultSearchController.searchBar.placeholder = "Search for movies"
self.theatersTable.tableHeaderView = self.resultSearchController.searchBar
self.theatersTable.reloadData()
getMovieInfo()
customIndicator()
infiniteScroll()
}
func customIndicator() {
self.theatersTable.infiniteScrollIndicatorView = CustomInfiniteIndicator(frame: CGRectMake(0, 0, 24, 24))
self.theatersTable.infiniteScrollIndicatorMargin = 40
}
func infiniteScroll() {
self.theatersTable.infiniteScrollIndicatorStyle = .White
self.theatersTable.addInfiniteScrollWithHandler { (scrollView) -> Void in
self.getMovieInfo()
}
}
func getMovieInfo() {
Alamofire.request(.GET, "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/in_theaters.json?page_limit=10&page=1&country=us&apikey=\(key)").responseJSON() {
(responseData) -> Void in
if let swiftyResponse = responseData.result.value {
let movies = Movies(JSONDecoder(swiftyResponse))
for movie in movies.allMovies {
self.results.append(movie)
}
}
self.theatersTable.reloadData()
self.theatersTable.finishInfiniteScroll()
}
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
self.searchResults.removeAll(keepCapacity: false)
if (searchController.searchBar.text?.characters.count > 0) {
Alamofire.request(.GET, "http://api.rottentomatoes.com/api/public/v1.0/movies.json?q=N&page_limit=10&page=1&apikey=\(key)").responseJSON() {
(responseData) -> Void in
print(responseData)
if let swiftyResponse = responseData.result.value {
let searches = Searches(JSONDecoder(swiftyResponse))
for search in searches.allSearches {
self.searchResults.append(search)
}
}
self.theatersTable.reloadData()
self.theatersTable.finishInfiniteScroll()
}
}
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (self.resultSearchController.active) {
return self.searchResults.count
} else {
return self.results.count
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
let titleLabel = cell.viewWithTag(1) as! UILabel
let yearLabel = cell.viewWithTag(2) as! UILabel
let durationLabel = cell.viewWithTag(3) as! UILabel
let posterImage = cell.viewWithTag(5) as! UIImageView
let starsTag = cell.viewWithTag(6) as! CosmosView
if (self.resultSearchController.active) {
titleLabel.text = searchResults[indexPath.row].titleMovie
yearLabel.text = searchResults[indexPath.row].yearMovie
durationLabel.text = searchResults[indexPath.row].durationMovie?.description
posterImage.sd_setImageWithURL(NSURL(string: searchResults[indexPath.row].posterMovie!))
starsTag.rating = searchResults[indexPath.row].ratingMovie!
starsTag.settings.updateOnTouch = false
} else {
titleLabel.text = results[indexPath.row].titleMovie
yearLabel.text = results[indexPath.row].yearMovie
durationLabel.text = results[indexPath.row].durationMovie?.description
posterImage.sd_setImageWithURL(NSURL(string: results[indexPath.row].posterMovie!))
starsTag.rating = results[indexPath.row].ratingMovie!
starsTag.settings.updateOnTouch = false
}
return cell
}
I also have some structs with information for the request tell me if you need something from that too.
Found the answer should have reloadData before the request.
func updateSearchResultsForSearchController(searchController: UISearchController) {
self.searchResults.removeAll(keepCapacity: false)
self.theatersTable.reloadData()//should have added this before the request
if (searchController.searchBar.text?.characters.count > 0) {
Alamofire.request(.GET, "http://api.rottentomatoes.com/api/public/v1.0/movies.json?q=\(searchController.searchBar.text!)&page_limit=10&page=1&apikey=\(key)").responseJSON() {
(responseData) -> Void in
if let swiftyResponse = responseData.result.value {
let searches = Searches(JSONDecoder(swiftyResponse))
for search in searches.allSearches {
self.searchResults.append(search)
}
}
self.theatersTable.reloadData()
self.theatersTable.finishInfiniteScroll()
}
}
}
Related
I have two tableview in my viewcontroller, and two dropdown menu from which i select a csv files for each tableview to display its contents.
I am getting an error of index out of reach. After debugging i came to know if both files have equal number of rows it doesn't show any errors.
How can i resolve this error because i have many csv files which may not contain equal amount of data.
import UIKit
import DropDown
class CompareFilesViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var DropDownView: UIView!
#IBOutlet weak var DropDownView2: UIView!
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var tableView2: UITableView!
#IBOutlet weak var selectedFile_lbl: UILabel!
#IBOutlet weak var selectedFile_lbl2: UILabel!
var filesDropDown = DropDown()
var filesDropDown2 = DropDown()
var files1 = [String]()
var files2 = [String]()
var files1Data = [String]()
var files2Data = [String]()
var refreshControl: UIRefreshControl?
var dropDownFlag = false
var dropDownFlag1 = false
var filename: String?
var filename1: String?
override func viewDidLoad() {
super.viewDidLoad()
var files = [String]()
files1Data.append("Select Files from drop down")
files2Data.append("Select Files from drop down")
// Do any additional setup after loading the view.
let fm = FileManager.default
let path = getDocumentsDirectory()
do{
let items = try fm.contentsOfDirectory(at: path, includingPropertiesForKeys: nil)
let onlyFileNames = items.filter{ !$0.hasDirectoryPath }
let onlyFileNamesStr = onlyFileNames.map { $0.lastPathComponent }
files.append(contentsOf: onlyFileNamesStr)
//getting different file names
for index in 0..<files.count{
if files[0].components(separatedBy: "_")[0] == files[index].components(separatedBy: "_")[0]{
print(true)
files1.insert(files[index], at: 0)
}
else{
print(false)
files2.insert(files[index], at: 0)
}
}
print("file names\(onlyFileNamesStr)")
}
catch
{
print(error)
}
setDropDown1()
setDropDown2()
tableView.delegate = self
tableView.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
tableView2.delegate = self
tableView2.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell2")
}
#IBAction func DropDownViewTapped(_ sender: Any) {
filesDropDown.show()
}
#IBAction func DropDownView2Tapped(_ sender: Any) {
filesDropDown2.show()
}
#IBAction func compareFiles(_ sender: Any) {
files2Data.removeAll()
files1Data.removeAll()
files2Data.insert(contentsOf: self.getSelectedFileContent(fileName: filename1!), at: 0)
files1Data.insert(contentsOf: self.getSelectedFileContent(fileName: filename!), at: 0)
tableView.reloadData()
tableView2.reloadData()
}
//for right dropdown
func setDropDown1() {
filesDropDown.textFont = UIFont.systemFont(ofSize: 10)
filesDropDown.textColor = .blue
filesDropDown.dataSource = files1
filesDropDown.anchorView = DropDownView2
filesDropDown.selectionAction = { index, title in
self.dropDownFlag = true
print("index: \(index), title: \(title)")
self.filename = title
self.selectedFile_lbl2.text = self.filename
// self.files1Data.insert(contentsOf: self.getSelectedFileContent(fileName: title), at: 0)
//self.tableView2.reloadData()
}
}
//for left drop down
func setDropDown2(){
filesDropDown2.textFont = UIFont.systemFont(ofSize: 10)
filesDropDown2.dataSource = files2
filesDropDown2.anchorView = DropDownView
filesDropDown2.selectionAction = { index, title in
self.dropDownFlag1 = true
print("index: \(index), title: \(title)")
self.filename1 = title
self.selectedFile_lbl.text = self.filename1
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var count: Int?
if tableView == self.tableView{
count = files1Data.count
print(count as Any)
}
if tableView == self.tableView2{
count = files2Data.count
print(count as Any)
}
print(count as Any)
return count!
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell:UITableViewCell?
if tableView == self.tableView{
cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell!.textLabel?.text = files2Data[indexPath.row]//error: index out of range
cell!.textLabel!.numberOfLines = 0
// cell!.textLabel?.adjustsFontSizeToFitWidth = true
cell!.textLabel?.font = UIFont(name: "Arial", size: 10.0)
}
if tableView == self.tableView2{
cell = tableView.dequeueReusableCell(withIdentifier: "Cell2", for: indexPath)
cell!.textLabel?.text = files1Data[indexPath.row]//error: index out of range
cell!.textLabel!.numberOfLines = 0
// cell!.textLabel?.adjustsFontSizeToFitWidth = true
cell!.textLabel?.font = UIFont(name: "Arial", size: 10.0)
}
return cell!
}
func getSelectedFileContent(fileName: String) -> [String] {
var contentsArray = [String]()
let fm = FileManager.default
let destURL = getDocumentsDirectory().appendingPathComponent(fileName)
do {
if fm.fileExists(atPath: destURL.path) {
let contents = try String(contentsOf: destURL)
contentsArray = contents.components(separatedBy: "\n")
print(contents)
}
} catch {
print("File copy failed.")
}
return contentsArray
}
}
I have tried to add refreshcontroll but this doesnt work.
For dropDown i have used AssistoLab library https://github.com/AssistoLab/DropDown.git
What i really want is to select csv files and display it to tableviews for comparison when button is clicked
is there any better solution which i can used?
You can modify your condition as below :
if tableView == self.tableView {
if files2Data.count <= indexPath.row {
// Your code
}else{
return UITableViewCell()
}
}
Same logic for the other table.
I dont know why, but after refactoring my code it works like i wanted to be. i just added two buttons for both files to be displayed after selecting from dropdown menu.
import UIKit
import DropDown
class DemoViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var topDropDownView: UIView!
#IBOutlet weak var bottomDropDownView: UIView!
#IBOutlet weak var selectFile_lbl1: UILabel!
#IBOutlet weak var selectFile_lbl2: UILabel!
#IBOutlet weak var tableView1: UITableView!
#IBOutlet weak var tableView2: UITableView!
var data1 = [String]()
var data2 = [String]()
var topDropDown = DropDown()
var bottomDropDown = DropDown()
var files1 = [String]()
var files2 = [String]()
var filename1 = ""
var filename2 = ""
override func viewDidLoad() {
super.viewDidLoad()
getFileNames()
setDropDown1()
setDropDown2()
tableView1.delegate = self
tableView2.delegate = self
tableView1.dataSource = self
tableView2.dataSource = self
tableView1.register(UITableViewCell.self, forCellReuseIdentifier: "cell1")
tableView2.register(UITableViewCell.self, forCellReuseIdentifier: "cell2")
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
#IBAction func button1(_ sender: Any) {
data1.removeAll()
data1.append(contentsOf: getSelectedFileContent(fileName: filename1))
tableView1.reloadData()
}
#IBAction func button2(_ sender: Any) {
data2.removeAll()
data2.append(contentsOf: getSelectedFileContent(fileName: filename2))
tableView2.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var count: Int?
if tableView == self.tableView1{
count = data1.count
print(count as Any)
}
if tableView == self.tableView2{
count = data2.count
print(count as Any)
}
print(count as Any)
return count!
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell:UITableViewCell?
if tableView == self.tableView1{
cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath)
cell!.textLabel?.text = data1[indexPath.row]
cell!.textLabel!.numberOfLines = 0
// cell!.textLabel?.adjustsFontSizeToFitWidth = true
cell!.textLabel?.font = UIFont(name: "Arial", size: 10.0)
}
if tableView == self.tableView2{
cell = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath)
cell!.textLabel?.text = data2[indexPath.row]
cell!.textLabel!.numberOfLines = 0
// cell!.textLabel?.adjustsFontSizeToFitWidth = true
cell!.textLabel?.font = UIFont(name: "Arial", size: 10.0)
}
return cell!
}
func getSelectedFileContent(fileName: String) -> [String] {
var contentsArray = [String]()
let fm = FileManager.default
let destURL = getDocumentsDirectory().appendingPathComponent(fileName)
do {
if fm.fileExists(atPath: destURL.path) {
let contents = try String(contentsOf: destURL)
contentsArray = contents.components(separatedBy: "\n")
print(contents)
}
} catch {
print("File copy failed.")
}
return contentsArray
}
#IBAction func topDropDownView_tapped(_ sender: Any) {
topDropDown.show()
}
#IBAction func bottomDropDownView_tapped(_ sender: Any) {
bottomDropDown.show()
}
func getFileNames(){
var files = [String]()
let fm = FileManager.default
let path = getDocumentsDirectory()
do{
let items = try fm.contentsOfDirectory(at: path, includingPropertiesForKeys: nil)
let onlyFileNames = items.filter{ !$0.hasDirectoryPath }
let onlyFileNamesStr = onlyFileNames.map { $0.lastPathComponent }
files.append(contentsOf: onlyFileNamesStr)
for index in 0..<files.count{
if files[0].components(separatedBy: "_")[0] == files[index].components(separatedBy: "_")[0]{
print(true)
files1.insert(files[index], at: 0)
}
else{
print(false)
files2.insert(files[index], at: 0)
}
}
print("file names\(onlyFileNamesStr)")
}
catch
{
print(error)
}
}
//for right dropdown
func setDropDown1() {
topDropDown.textFont = UIFont.systemFont(ofSize: 10)
topDropDown.textColor = .blue
topDropDown.dataSource = files1
topDropDown.anchorView = topDropDownView
topDropDown.selectionAction = { index, title in
print("index: \(index), title: \(title)")
self.filename1 = title
self.selectFile_lbl1.text = self.filename1
// self.files1Data.insert(contentsOf: self.getSelectedFileContent(fileName: title), at: 0)
//self.tableView2.reloadData()
}
}
//for left drop down
func setDropDown2(){
bottomDropDown.textFont = UIFont.systemFont(ofSize: 10)
bottomDropDown.dataSource = files2
bottomDropDown.anchorView = bottomDropDownView
bottomDropDown.selectionAction = { index, title in
print("index: \(index), title: \(title)")
self.filename2 = title
self.selectFile_lbl2.text = self.filename2
//self.files2Data.insert(contentsOf: self.getSelectedFileContent(fileName: title), at: 0)
// self.tableView2.reloadData()
}
}
}
I am having trouble displaying the data I got from my REST API. I can retrieve the data with no problem but the tableview is not displaying the data. How do I get the data inside the tableview cell in the tableview?
class SearchBSViewController: UIViewController {
#IBOutlet weak var searchBar: UISearchBar!
#IBOutlet weak var tableView: UITableView!
lazy var tapRecognizer: UITapGestureRecognizer = {
var recognizer = UITapGestureRecognizer(target:self, action: #selector(dismissKeyBoard))
return recognizer
}()
var searchResults: [Service] = []
let busStop = BusStop(odataMetadata: "", busStopCode: "", services: [])
let queryService = QueryService()
override func viewDidLoad() {
super.viewDidLoad()
alterLayout()
searchBar.delegate = self
}
func alterLayout() {
tableView.tableHeaderView = UIView()
tableView.estimatedSectionHeaderHeight = 50
navigationItem.titleView = searchBar
searchBar.showsScopeBar = false
searchBar.placeholder = "Search for bus stop by bus code"
}
}
extension SearchBSViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.searchResults.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell: BusCell = tableView.dequeueReusableCell(withIdentifier: "BusCell", for: indexPath) as? BusCell else {
return UITableViewCell()
}
let bus = searchResults[indexPath.row]
cell.busNoLbl.text = bus.serviceNo
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexpath: IndexPath) -> CGFloat {
return 100
}
}
extension SearchBSViewController: UISearchBarDelegate {
#objc func dismissKeyBoard() {
searchBar.resignFirstResponder()
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
dismissKeyBoard()
print("Something")
guard let searchText = searchBar.text, !searchText.isEmpty else { return }
UIApplication.shared.isNetworkActivityIndicatorVisible = true
guard let searchNumber: Int = Int(searchText) else { return }
queryService.GetBusStop(BusNo: searchNumber) {
results in
UIApplication.shared.isNetworkActivityIndicatorVisible = false
if let results = results {
print(results.services?[1].nextBus?.estimatedArrival ?? 0)
self.searchResults = results.services!
self.tableView.reloadData()
self.tableView.setContentOffset(CGPoint.zero, animated: false)
}
}
}
func position(for bar: UIBarPositioning) -> UIBarPosition {
return .topAttached
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
view.addGestureRecognizer(tapRecognizer)
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
view.removeGestureRecognizer(tapRecognizer)
}
}
class BusCell: UITableViewCell {
#IBOutlet weak var busNoLbl: UILabel!
#IBOutlet weak var firstBusLbl: UILabel!
#IBOutlet weak var secBusLbl: UILabel!
#IBOutlet weak var thirdBusLbl: UILabel!
#IBOutlet weak var firstPrg: UIProgressView!
#IBOutlet weak var secPrg: UIProgressView!
#IBOutlet weak var thirdPrg: UIProgressView!
#IBOutlet weak var firstType: UILabel!
#IBOutlet weak var secType: UILabel!
#IBOutlet weak var thirdType: UILabel!
func configure(services: Service) {
busNoLbl.text = services.serviceNo
firstBusLbl.text = services.nextBus?.estimatedArrival
secBusLbl.text = services.nextBus2?.estimatedArrival
thirdBusLbl.text = services.nextBus3?.estimatedArrival
}
}
class QueryService {
typealias QueryResult = (BusStop?) -> ()
var buses: BusStop = BusStop(odataMetadata: "", busStopCode: "", services: [])
let defaultSession = URLSession(configuration: .default)
var dataTask: URLSessionDataTask?
func GetBusStop(BusNo: Int, completionBlock: #escaping QueryResult){
dataTask?.cancel()
var urlComponents = URLComponents(string: "http://datamall2.mytransport.sg/ltaodataservice/BusArrivalv2")!
urlComponents.queryItems = [URLQueryItem(name: "BusStopCode", value: String(BusNo))]
guard let url = urlComponents.url else { return}
let urlRequest = Header(url: url) //input the header for authorization
dataTask = defaultSession.dataTask(with: urlRequest) { (data, response, error) in
if error != nil {
print(error!.localizedDescription)
}
guard let data = data else { return }
do {
let BusStopData = try
JSONDecoder().decode(BusStop.self, from: data)
DispatchQueue.main.async {
print("Queue")
completionBlock(BusStopData)
}
} catch let jsonError {
print(jsonError)
}
}
dataTask?.resume()
}
}
First thing is you need to set up a delegate and data source method for the table view. setup it in your view did load method
tableView.delegate = self
tableView.datasource = self
Second is you need to reload your table view after you hit your API call
tableView.reloadData()
Please set delegate and datasoruce of table view in alterLayout() function, like
tableView.delegate = self
tableView.datasource = self
I am new to swift programming and would need some help to check what is wrong in my tableviewcell. I have tried alot of great suggestions on stackoverflow.( make sure your outlets are connected, set delegate and datasource of your tableview to self)
This is my ViewController:
import UIKit
class CharacterViewController: UIViewController, UITableViewDataSource, UITableViewDelegate , APIControllerProtocol {
#IBOutlet weak var CharacterInfoView: UITableView!
var apiController:APIController!
var dataArray: [[String:Any]]?
var processcharacter= [CharacterListModel]()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor=UIColor.white
self.CharacterInfoView.estimatedRowHeight = 44
self.CharacterInfoView.rowHeight = UITableViewAutomaticDimension
self.CharacterInfoView.dataSource = self
self.CharacterInfoView.delegate = self
apiController = APIController()
apiController.delegate=self
self.navigationItem.title = "Character"
self.view.showLoading()
apiController.getCharacterData{ (statusCode, data, response, error) -> () in
self.view.stopLoading()
if(statusCode == nil)
{
self.view.showServiceNotAvailableMessage(self)
}
if !(error == nil)
{
self.view.showServiceNotAvailableMessage(self)
}
if statusCode == 200
{
do
{
self.processcharacter= CharacterListData.processData(data: data)
self.CharacterInfoView.reloadData()
}
catch(_ as NSError)
{
}
}
else
{
return
}
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.dataArray == nil
{
return 0
}
else
{
return processcharacter.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier:"Cell", for:indexPath) as! CharacterTableViewCell
var processcharacters= processcharacter[indexPath.row]
cell.location.text = processcharacters.location
cell.name.text = processcharacters.name
cell.characterID.text = processcharacters.characterID
cell.time.text = processcharacters.lastlocatedtime
if wecares.sos == true {
processcharacters.imagebutton = UIImage(named: "sos_icon")!
}
else{
processcharacters.imagebutton = UIImage(named: "null_button")!
}
cell.button.image = processcharacters.imagebutton
return cell
}
func reachabilityChanged(_ status: Bool) {
}
}
This is my subclass for my ViewController:
import Foundation
class CharacterListDataHelper: NSObject {
static func processData(data: AnyObject?) -> [CharacterListModel]
{
var modelList:[CharacterListModel] = [CharacterListModel]()
let darr = try? JSONSerialization.jsonObject(with: data! as! Data, options: .mutableLeaves) as! [[String:Any]]
var dataModel:CharacterListModel
for obj in darr!
{
dataModel = CharacterListModel()
dataModel.location = obj["playerLocation"] as! String
dataModel.name = obj["playerName"] as! String
dataModel.characterID= obj["playerID"] as! String
dataModel.lastlocatedtime = obj["lastUpdatedTime"] as! String
}
modelList.append(dataModel)
}
return modelList
}
}
This is my Model:
import Foundation
struct CharacterListModel {
var name: String?
var characterID: String?
var location: String?
var lastlocatedtime: String?
var imagebutton: UIImage?
var sos: Bool?
}
This is my TableViewCell:
class CharacterTableViewCell: UITableViewCell {
#IBOutlet weak var name: UILabel!
#IBOutlet weak var characterID: UILabel!
#IBOutlet weak var location: UILabel!
#IBOutlet weak var lastlocatedtime: UILabel!
#IBOutlet weak var button: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
Thanks in advance!
Don't fetch data in viewDidLoad() method. Fetch in viewWillAppear and reload after getting data.
Sorry newbie here in IOS Swift. Just want to ask how can i change my BatButtonItem title when one of my Popover cell is selected. Even though I used delegate method. But it still doesn't work for me.
EXAMPLE:
Here is My Storyboard
Mine doesn't work well here.
HERE IS MY HOMEVC.swift (Whole Code)
//
// HomeVC.swift
// SwiftLoginScreen
//
// Created by Dipin Krishna on 31/07/14.
// Copyright (c) 2014 Dipin Krishna. All rights reserved.
import UIKit
import AFNetworking
import FontAwesome_swift
import KeychainAccess
class HomeVC: UIViewController, UITableViewDataSource, UITableViewDelegate, UIPopoverPresentationControllerDelegate, LanguageViewControllerDelegate {
#IBOutlet weak var dashboardOpen: UIBarButtonItem!
#IBOutlet var usernameLabel : UILabel!
#IBOutlet weak var Open: UIBarButtonItem!
#IBOutlet weak var dashboard_icon1: UILabel!
#IBOutlet weak var card_view1: UIView!
#IBOutlet weak var sub_card_view1: UIView!
#IBOutlet weak var dashboard_icon2: UILabel!
#IBOutlet weak var card_view2: UIView!
#IBOutlet weak var sub_card_view2: UIView!
#IBOutlet weak var dashboard_icon3: UILabel!
#IBOutlet weak var card_view3: UIView!
#IBOutlet weak var sub_card_view3: UIView!
#IBOutlet weak var dashboard_icon4: UILabel!
#IBOutlet weak var theScrollView: UIScrollView!
#IBOutlet weak var card_view4: UIView!
#IBOutlet weak var sub_dashboard_icon: UILabel!
#IBOutlet weak var sub_dashboard_icon2: UILabel!
#IBOutlet weak var sub_dashboard_icon3: UILabel!
#IBOutlet weak var currentTimeLabel: UILabel!
#IBOutlet weak var currentTimeLabel2: UILabel!
#IBOutlet weak var currentTimeLabel3: UILabel!
#IBOutlet weak var card_view5: UITableView!
#IBOutlet weak var calendarView: NWCalendarView!
//#IBOutlet weak var ticketBtn: UIBarButtonItem!
#IBOutlet weak var barButtonItem: UIBarButtonItem!
#IBOutlet weak var companyWalletBalance: UILabel!
#IBOutlet weak var cashWalletBalance: UILabel!
#IBOutlet weak var signupWalletBalance: UILabel!
#IBOutlet weak var viewStatement1: UILabel!
#IBOutlet weak var viewStatement2: UILabel!
#IBOutlet weak var viewStatement3: UILabel!
#IBOutlet weak var languageTextField: UITextField!
public static var menuAPI = Json4Swift_Base.init()
public static var ticketAPI = TicketAPIResponse.init()
var timer = NSTimer()
var sections : [Section] = SectionsData().getSectionsFromData()
public static var tableData: [String] = []
public static var tableDate: [String] = []
let navigationBar = UINavigationBar(frame: CGRectMake(108, 0, 110, 64))
let navItem = UINavigationItem.init(title: "My Home")
//var pickOption = ["English", "简体", "繁体"]
//var segmentedControl: HMSegmentedControl = HMSegmentedControl(sectionTitles: ["One", "Two"])
override func viewDidLoad() {
super.viewDidLoad()
// For UIBar Button Item Title (English) //
let font = UIFont.boldSystemFontOfSize(14)
barButtonItem.setTitleTextAttributes([NSFontAttributeName: font], forState:UIControlState.Normal)
doLocalize()
//SwiftSpinner.showWithDelay(0.1, title: "Loading...")
//SwiftSpinner.hide()
// For UINavigation Bar //
navigationBar.barTintColor = UIColor(red: 1.0/255.0, green: 164.0/255.0, blue: 161.0/255.0, alpha: 0.5)
navigationBar.clipsToBounds = true
navigationBar.items = [navItem]
let titleDict: NSDictionary = [NSForegroundColorAttributeName: UIColor.whiteColor()]
navigationBar.titleTextAttributes = titleDict as! [String : AnyObject]
self.view.addSubview(navigationBar)
calendarView.layer.borderWidth = 1
calendarView.layer.borderColor = UIColor.lightGrayColor().CGColor
calendarView.backgroundColor = UIColor.whiteColor()
// For Calendar //
let date = NSDate()
print(date)
let newDate3 = date.dateByAddingTimeInterval(60*60)
calendarView.selectedDates = [newDate3]
calendarView.selectionRangeLength = 1
calendarView.createCalendar()
calendarView.scrollToDate(newDate3, animated: true)
// For Scrolling //
let subview = theScrollView.subviews[0] as! UIView;
//Make the scroll view's contentSize the same size as the content view.
theScrollView!.contentSize = subview.bounds.size;
// For Side Menu (With Swap) //
dashboardOpen.target = self.revealViewController()
dashboardOpen.action = Selector("revealToggle:")
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
// For Dashboard Icon //
dashboard_icon1.font = UIFont.fontAwesomeOfSize(40)
dashboard_icon1.text = String.fontAwesomeIconWithCode("fa-money")
dashboard_icon2.font = UIFont.fontAwesomeOfSize(40)
dashboard_icon2.text = String.fontAwesomeIconWithCode("fa-money")
dashboard_icon3.font = UIFont.fontAwesomeOfSize(40)
dashboard_icon3.text = String.fontAwesomeIconWithCode("fa-money")
dashboard_icon4.font = UIFont.fontAwesomeOfSize(40)
dashboard_icon4.text = String.fontAwesomeIconWithCode("fa-clock-o")
sub_dashboard_icon.font = UIFont.fontAwesomeOfSize(20)
sub_dashboard_icon.text = String.fontAwesomeIconWithCode("fa-arrow-circle-o-right")
sub_dashboard_icon2.font = UIFont.fontAwesomeOfSize(20)
sub_dashboard_icon2.text = String.fontAwesomeIconWithCode("fa-arrow-circle-o-right")
sub_dashboard_icon3.font = UIFont.fontAwesomeOfSize(20)
sub_dashboard_icon3.text = String.fontAwesomeIconWithCode("fa-arrow-circle-o-right")
// For Dashboard Radius //
card_view1.layer.masksToBounds = true;
card_view1.layer.cornerRadius = 5.0;
let path1 = UIBezierPath(roundedRect:sub_card_view1.bounds, byRoundingCorners:[.BottomRight, .BottomLeft], cornerRadii: CGSizeMake(5, 5))
let maskLayer1 = CAShapeLayer()
maskLayer1.path = path1.CGPath
sub_card_view1.layer.mask = maskLayer1
card_view2.layer.masksToBounds = true;
card_view2.layer.cornerRadius = 5.0;
let path2 = UIBezierPath(roundedRect:sub_card_view2.bounds, byRoundingCorners:[.BottomRight, .BottomLeft], cornerRadii: CGSizeMake(5, 5))
let maskLayer2 = CAShapeLayer()
maskLayer2.path = path2.CGPath
sub_card_view2.layer.mask = maskLayer2
card_view3.layer.masksToBounds = true;
card_view3.layer.cornerRadius = 5.0;
let path3 = UIBezierPath(roundedRect:sub_card_view3.bounds, byRoundingCorners:[.BottomRight, .BottomLeft], cornerRadii: CGSizeMake(5, 5))
let maskLayer3 = CAShapeLayer()
maskLayer3.path = path3.CGPath
sub_card_view3.layer.mask = maskLayer3
card_view4.layer.masksToBounds = true;
card_view4.layer.cornerRadius = 5.0;
card_view5.layer.masksToBounds = true;
card_view5.layer.cornerRadius = 5.0;
calendarView.layer.masksToBounds = true;
calendarView.layer.cornerRadius = 5.0;
// For Dashboard Current Time //
self.timer = NSTimer.scheduledTimerWithTimeInterval(1.0,
target: self,
selector: Selector("tick"),
userInfo: nil,
repeats: true)
// Do any additional setup after loading the view.
}
func changeName(text: String) {
self.barButtonItem.title = "\(text)" // For get barButton you should create IBOutlet for barButtonItem
print(self.barButtonItem.title)
}
#objc func tick() {
let date1 = NSDate()
let dateFormatter1 = NSDateFormatter()
dateFormatter1.dateFormat = "dd MMMM yyyy"
let timeZone1 = NSTimeZone(name: "GMT+8")
dateFormatter1.timeZone = timeZone1
let date2 = NSDate()
let dateFormatter2 = NSDateFormatter()
dateFormatter2.dateFormat = "EEEE"
let timeZone2 = NSTimeZone(name: "GMT+8")
dateFormatter2.timeZone = timeZone2
currentTimeLabel.text = dateFormatter1.stringFromDate(date1)
currentTimeLabel2.text = dateFormatter2.stringFromDate(date2)
currentTimeLabel3.text = NSDateFormatter.localizedStringFromDate(NSDate(),
dateStyle: .NoStyle,
timeStyle: .MediumStyle)
var day:String = ""
day = currentTimeLabel2.text!
if (day.containsString("Sunday")){
currentTimeLabel2.text = Localization("Sunday")
}
else if (day.containsString("Monday")){
currentTimeLabel2.text = Localization("Monday")
}
else if (day.containsString("Tuesday")){
currentTimeLabel2.text = Localization("Tuesday")
}
else if (day.containsString("Wednesday")){
currentTimeLabel2.text = Localization("Wednesday")
}
else if (day.containsString("Thursday")){
currentTimeLabel2.text = Localization("Thursday")
}
else if (day.containsString("Friday")){
currentTimeLabel2.text = Localization("Friday")
}
else{
currentTimeLabel2.text = Localization("Saturday")
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
let parameters1 = ["ActionType":"default","LanguageCode":stringLang,"Token":result]
manager.POST(CONFIG_URL,
parameters: parameters1,
success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in
print("JSON: " + responseObject.description)
var responseDict = responseObject as! Dictionary<String, AnyObject>
let dashboardAPI = DashboardAPIResponse(dictionary: responseDict)
},
failure: { (operation: AFHTTPRequestOperation?,error: NSError!) -> Void in
print("Error: " + error.localizedDescription)
})
let parameters = ["ActionType":"menu","LanguageCode":stringLang,"Token":result]
manager.POST(CONFIG_URL,
parameters: parameters,
success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in
print("JSON: " + responseObject.description)
var responseDict = responseObject as! Dictionary<String, AnyObject>
HomeVC.menuAPI = Json4Swift_Base(dictionary: responseDict)
var tempArray = HomeVC.menuAPI?.result
for var i = 0; i < tempArray!.count ; ++i {
let level1 = tempArray![i].module
let level2 = tempArray![i].subModule
for var i = 0; i < level1!.count ; ++i {
print(level1![i].icon)
print(level1![i].label)
}
for var i = 0; i < level2!.count ; ++i {
print(level2![i].label)
var level3 = level2![i].function
for var i = 0; i < level3!.count ; ++i {
print(level3![i].label)
print(level3![i].menuLink)
print(level3![i].uRL)
}
}
}
},
failure: { (operation: AFHTTPRequestOperation?,error: NSError!) -> Void in
print("Error: " + error.localizedDescription)
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func doLocalize(){
companyWalletBalance.text = Localization("companyWalletBalance")
cashWalletBalance.text = Localization("cashWalletBalance")
signupWalletBalance.text = Localization("signupWalletBalance")
currentTimeLabel2.text = Localization("currentTimeLabel2")
viewStatement1.text = Localization("viewStatement")
viewStatement2.text = Localization("viewStatement")
viewStatement3.text = Localization("viewStatement")
navItem.title = Localization("navItem")
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section].heading
}
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
// Text Color
var header: UITableViewHeaderFooterView = (view as! UITableViewHeaderFooterView)
header.textLabel!.textColor = UIColor.whiteColor()
header.contentView.backgroundColor = UIColor.blackColor()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return sections.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var mycell = tableView.dequeueReusableCellWithIdentifier("sectionsCell", forIndexPath: indexPath) as! MyCustomTableViewCell
mycell.label1.text = sections[indexPath.section].items[indexPath.row]
mycell.label2.text = sections[indexPath.section].items[indexPath.row]
mycell.label3.text = sections[indexPath.section].items[indexPath.row]
mycell.label4.text = sections[indexPath.section].items[indexPath.row]
return mycell
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40.0
}
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle
{
return UIModalPresentationStyle.None
}
#IBAction func languageButton(sender: AnyObject) {
let storyboard : UIStoryboard = UIStoryboard(name: "Storyboard", bundle: nil)
var menuViewController: LanguageViewController = storyboard.instantiateViewControllerWithIdentifier("LanguageViewController") as! LanguageViewController
menuViewController.delegate = self // Put this Line
menuViewController.modalPresentationStyle = .Popover
menuViewController.preferredContentSize = CGSizeMake(50, 100)
let popoverMenuViewController = menuViewController.popoverPresentationController
popoverMenuViewController?.permittedArrowDirections = .Any
popoverMenuViewController?.delegate = self
popoverMenuViewController?.sourceView = menuViewController.view
popoverMenuViewController?.sourceRect = CGRect(x:240, y:35, width: 1, height: 1)
presentViewController(menuViewController, animated: true, completion: nil)
}
#IBAction func dashboardLogout(sender: AnyObject) {
let parameters = ["ActionType":"logout"]
manager.POST(CONFIG_URL,
parameters: parameters,
success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in
print("JSON: " + responseObject.description)
// CLEAN COOKIES //
let cookie = NSHTTPCookie.self
let cookieJar = NSHTTPCookieStorage.sharedHTTPCookieStorage()
for cookie in cookieJar.cookies! {
print(cookie.name+"="+cookie.value)
cookieJar.deleteCookie(cookie)
}
var revealViewControler :SWRevealViewController = self.revealViewController()
let webViewController = self.storyboard!.instantiateViewControllerWithIdentifier("SWRevealViewController") as! SWRevealViewController
revealViewControler.pushFrontViewController(webViewController, animated: true)
},
failure: { (operation: AFHTTPRequestOperation?,error: NSError!) -> Void in
print("Error: " + error.localizedDescription)
})
}
}
// For Date + Time //
extension NSDate {
var formattedd:String {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter.stringFromDate(self)
}
func formatteddWith(format:String) -> String {
let formatter = NSDateFormatter()
formatter.dateFormat = format
return formatter.stringFromDate(self)
}
}
// For Date + Time //
extension String {
var asDatee:NSDate! {
let styler = NSDateFormatter()
styler.dateFormat = "yyyy-MM-dd"
return styler.dateFromString(self)!
}
func asDateFormatteddWith(format:String) -> NSDate! {
let styler = NSDateFormatter()
styler.dateFormat = format
return styler.dateFromString(self)!
}
}
HERE IS MY LANGUAGEVIEWCONTROLLER.swift (Where display the content of Popover)
//
// LanguageViewController.swift
// SwiftLoginScreen
//
// Created by User on 3/21/16.
// Copyright © 2016 Dipin Krishna. All rights reserved.
//
import UIKit
import AFNetworking
protocol LanguageViewControllerDelegate{
func changeName(text:String)
}
class LanguageViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var delegate:LanguageViewControllerDelegate! = nil
var arrLanguage: [String] = ["English", "简体", "繁体"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableFooterView = UIView()
// Do any additional setup after loading the view, typically from a nib.
//self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
}
func tableView(tableView: UITableView, didselectRowAtIndexPath indexPath: NSIndexPath) {
delegate!.changeName(arrLanguage[indexPath.row])
tableView.delegate = self
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrLanguage.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:LanguageTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("LanguageTableViewCell") as! LanguageTableViewCell
cell.languageLabel.text = arrLanguage[indexPath.row]
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// For Popover Frame Size //
override var preferredContentSize: CGSize {
get
{
return CGSize(width: 150, height: 130)
}
set
{
super.preferredContentSize = newValue
}
}
}
HERE IS MY LANGUAGETABLEVIEWCELL.swift
//
// LanguageTableViewCell.swift
// SwiftLoginScreen
//
// Created by User on 3/21/16.
// Copyright © 2016 Dipin Krishna. All rights reserved.
//
import UIKit
class LanguageTableViewCell: UITableViewCell {
#IBOutlet weak var languageLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
When i try to debug this part of code, when my code run, it doesn't go through this code. why ?
func changeName(text: String) {
self.barButtonItem.title = "\(text)" // For get barButton you should create IBOutlet for barButtonItem
print(self.barButtonItem.title)
}
PLEASE HELP.
Step 1: Make a protocol in the LanguageViewController that you will be sending the data.
protocol LanguageViewControllerDelegate{
func changeName(text:String)
}
Step2: Declare the delegate in the sending class (i.e. HOMEVC)
class LanguageViewController: UIViewController {
var delegate:LanguageViewControllerDelegate! = nil
[...]
}
Step3: Use the delegate in a class method to send the data to the receiving method, which is any method that adopts the protocol.
func tableView(tableView: UITableView, didselectRowAtIndexPath indexPath: NSIndexPath) {
delegate!.changeName(arrLanguage[indexPath.row])
}
Step 4: Adopt the protocol in the receiving class
class HomeViewController: UIViewController,LanguageViewControllerDelegate { }
Step 5: Implement the delegate method ( HomeViewController - as in your Problem )
func changeName(text: String) {
self.barButton.title = "\(text)" // For get barButton you should create IBOutlet for barButtonItem
}
Step 6: Set the delegate in the action button for the BarButtonItem for Popover:
#IBAction func languageButton(sender: AnyObject) {
let storyboard : UIStoryboard = UIStoryboard(name: "Storyboard", bundle: nil)
var menuViewController: LanguageViewController = storyboard.instantiateViewControllerWithIdentifier("LanguageViewController") as! LanguageViewController
menuViewController.modalPresentationStyle = .Popover
menuViewController.preferredContentSize = CGSizeMake(50, 100)
menuViewController.delegate = self // Put this Line
let popoverMenuViewController = menuViewController.popoverPresentationController
popoverMenuViewController?.permittedArrowDirections = .Any
popoverMenuViewController?.sourceView = menuViewController.view
popoverMenuViewController?.delegate = self
popoverMenuViewController?.sourceRect = CGRect(x:240, y:35, width: 1, height: 1)
presentViewController(menuViewController, animated: true, completion: nil)
}
Yoy should put tableView delegate and datasourse in viewDidLoad() :-
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView()
}
And tableView didSelectRow :-
func tableView(tableView: UITableView, didselectRowAtIndexPath indexPath: NSIndexPath) {
delegate!.changeName(arrLanguage[indexPath.row])
}
And Hope that this gonna work ....
I want to know which imageview was clicked by the user I am using the following code, but it is not calling the leftTapView and rightTapView functions
class CustomTableViewCell : UITableViewCell {
#IBOutlet var leftTeamImage: UIImageView!
#IBOutlet var rightTeamImage: UIImageView!
#IBOutlet var rightTeamNameLabel: UILabel!
#IBOutlet var leftTeamNameLabel: UILabel!
#IBOutlet var leftTeamScoreLabel: UILabel!
#IBOutlet var rightTeamScoreLabel: UILabel!
#IBOutlet var leftView : UIView!
#IBOutlet var rightView : UIView!
let lettTapRec = UITapGestureRecognizer()
let rightTapRec = UITapGestureRecognizer()
ScoreLabel.text = leftTeamScore
rightTeamNameLabel.text = rightTeamName.uppercaseString
rightTeamScoreLabel.text = rightTeamScore
}
func load(#leftTeamName: String, rightTeamName: String, leftTeamScore: Int, rightTeamScore: Int) {
leftTeamNameLabel.text = leftTeamName.uppercaseString
leftTeamScoreLabel.text = String(leftTeamScore)
rightTeamNameLabel.text = rightTeamName.uppercaseString
rightTeamScoreLabel.text = String(rightTeamScore)
lettTapRec.addTarget(self, action: "leftTapView")
leftView.userInteractionEnabled = true
leftView.addGestureRecognizer(lettTapRec)
//
rightTapRec.addTarget(self, action: "rightTapView")
rightView.userInteractionEnabled = true
rightView.addGestureRecognizer(rightTapRec)
}
func leftTapView(sender: AnyObject){
println("left")
}
func rightTapView(sender: AnyObject){
println("left")
}
}
protocol ImageTappedProtocols {
func leftImageTapped(imageView : UIImage)
func rightImageTapped(imageView: UIImage)
}
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet var tableView : UITableView!
var items: [(String, String)] = [
("My", "swift 1.jpeg"),
("Name", "swift 2.jpeg"),
("is", "swift 3.jpeg"),
("Atif", "swift 4.jpeg"),
("Farrukh", "swift 5.jpeg")
]
var team1 :[String] = []
var team2 :[String] = []
var id : [String] = []
var team1_bets : [Int] = []
var team2_bets : [Int] = []
var end_date : [String] = []
var list = Dictionary<String, String>()
var count : Int = 0
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:CustomTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("customCell") as CustomTableViewCell
// this is how you extract values from a tuple
var (title, image) = items[indexPath.row]
var teama: String = team1[indexPath.row]
var teamb: String = team2[indexPath.row]
var teamAScore : Int = team1_bets[indexPath.row]
var teamBScore : Int = team2_bets[indexPath.row]
cell.backgroundColor = UIColor(red: 123, green: 225, blue: 38, alpha: 0.2)
return cell
}
func tableView(tableView : UITableView, didSelectedRowAtIndexPath indexPath : NSIndexPath){
//tableView.deselectRowAtIndexPath(indexPath, animated: true)
println("You selected cell #\(indexPath.row)!")
let indexPath = tableView.indexPathForSelectedRow();
let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!;
println(currentCell.textLabel.text)
}
func tableView(tableView : UITableView, didSelectRowAtIndexPath indexPath : NSIndexPath){
//tableView.deselectRowAtIndexPath(indexPath, animated: true)
println("You selected cell #\(indexPath.row)!")
let indexPath = tableView.indexPathForSelectedRow();
let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!
println(currentCell.contentView)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let urlAsString = "http://codespikestudios.com/betting_app/bet/get_events/1"
//let urlAsString = "http://api.topcoder.com/v2/challenges?pageSize=2"
let url: NSURL = NSURL(string: urlAsString)!
let urlSession = NSURLSession.sharedSession()
//2
let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
if (error != nil) {
println(error.localizedDescription)
}
var err: NSError?
// 3
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSArray
if (err != nil) {
println("JSON Error \(err!.localizedDescription)")
}
// 4
println(jsonResult)
println(jsonResult.count)
println(jsonResult[1].valueForKey("cat_name") as String)
var dictionary = Dictionary<String, String>()
self.count = jsonResult.count
for var i = 0; i < self.count; i++ {
self.team1 = jsonResult.valueForKey("team1") as Array
self.team2 = jsonResult.valueForKey("team2") as Array
self.team1_bets = jsonResult.valueForKey("team1_bets") as Array
self.team2_bets = jsonResult.valueForKey("team2_bets") as Array
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
})
//let jsonDate: String! = jsonResult["date"] as NSString
//let jsonTime: String! = jsonResult["time"] as NSString
//println(jsonTime)
})
// 5
jsonQuery.resume()
var nib = UINib(nibName: "MyTableViewCell", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "customCell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
this is all I get
You selected cell #3!
<UITableViewCellContentView: 0x7f871b687350; frame = (0 0; 580 136.5); opaque = NO; gestureRecognizers = <NSArray: 0x7f871b68c180>; layer = <CALayer: 0x7f871b687420>>
You will want to add a target when you initialize your gesture recognizers. That would look like, for instance:
let leftTapRect = UIGestureRecognizer(target: self, action: "leftTapView:")
In addition, you will need to add a sender argument to your event handlers leftTapView and rightTapView:
func leftTapView(sender: AnyObject) {
...
}
solved my problem, Actually i had set my view's alpha to 0, when I set it to 1 and made the set the background as Clear Colour it started working. Rest the working perfectly. If someone can explain the reason of why setting alpha doesnt trigger the tap gesture I will gladly accept hi/her answer as accepted.
A view with an alpha of 0.0 won't receive touch events.
From the Event Handling guide:
"Note that a view also does not receive touch events if it’s hidden or transparent."
From the Creating Views documentation:
"A hidden view does not receive touch events from the system."