get the clicked imageview swift - ios

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."

Related

Error while selecting two files from dropdown to display on UITableView in swift

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()
}
}
}

Swift hide/show UIView in cell (data from database)

I have UITableViewCell with UITextView and UIView
I'm try to hide/show UIView
Constraints — TextView:
Trailing to Superview Equals 2
Leading to Superview Equals 2
Top to Superview Equals 2
Bottom to Superview Equals 40
UIVIew:
Trailing to Superview
Leading to Superview
Bottom to Superview
Height 35
In Cell class I'm connect TextView BottomConstraint
UITableViewCell class :
#IBOutlet weak var myTextView: UITextView!
#IBOutlet weak var detailView: UIView!
#IBOutlet weak var detailLabel: UILabel!
#IBOutlet weak var TextViewConstraintToBottom: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
detailView.isHidden = true
if detailView.isHidden == true {
TextViewConstraintToBottom.constant = 0
} else {
TextViewConstraintToBottom.constant = 40
}
}
In ViewController with UITableView :
var handle: DatabaseHandle?
var ref: DatabaseReference?
var quoteList: [String] = []
var songArray: [String] = []
override func viewWillAppear(_ animated: Bool) {
myTableView.estimatedRowHeight = 100
myTableView.rowHeight = UITableViewAutomaticDimension
}
override func viewDidLoad() {
super.viewDidLoad()
myTableView.dataSource = self
myTableView.delegate = self
dataCatch()
}
func dataCatch() {
ref = Database.database().reference()
handle = ref?.child("Цитаты").child("\(cat)").child("\(quoteNAme)").observe(.childAdded, with: { (snapshot) in
let username = snapshot.value as? NSDictionary
if let us = username?["name"] {
self.quoteList.append(us as! String)
self.quoteList = self.quoteList.filter(){$0 != "1"}
self.myTableView.reloadData()
}
if let us = username?["song"].unsafelyUnwrapped {
self.celT?.detailView.isHidden = false
self.songArray.append(us as! String)
self.myTableView.reloadData()
}
})
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! QuoteTableVC
let indexP = indexPath.row
cell.myTextView.text = quoteList[indexP]
cell.detailLabel.text = songArray[indexP]
return cell
}
In database I have structure
I decided
In ViewController :
func dataCatch() {
ref = Database.database().reference()
handle = ref?.child("Цитаты").child("\(cat)").child("\(quoteNAme)").observe(.childAdded, with: { (snapshot) in
let username = snapshot.value as? NSDictionary
if let us = username?["name"] {
self.quoteList.append(us as! String)
self.quoteList = self.quoteList.filter(){$0 != "1"}
self.myTableView.reloadData()
}
if snapshot.hasChild("song") {
let us = username?["song"]
self.songArray.append(us as! String)
} else {
let tet = "1"
// self.celT?.detailView.isHidden = true
self.songArray.append(tet as! String)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
cell.detailLabel.text = songArray[indexP]
if cell.detailLabel.text != "1" {
cell.detailView.isHidden = false
cell.butConstraint.constant = 40
} else {
cell.detailView.isHidden = true
cell.butConstraint.constant = 0
}
In cellForRow
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UI TableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! QuoteTableVC
// hide = check your model whether it has song or not
if hide {
cell.TextViewConstraintToBottom.constant = 0
}
else {
cell.TextViewConstraintToBottom.constant = 40
}
}

IOS SWIFT : Change My BarButtonItem Title when one of my Popover cell is selected

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 ....

UISearchController number of rows not getting called

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()
}
}
}

How to parse a youtubeURL to load video from parse.com when button is clicked using swift

Im trying to find the best way to load a video from my parse database In my swift project. I have a column called ProductVideo in the data base that I have the url of the video in. My project has a list of products in a tableview and when one of those cells is pushed it bring you to a new view controller that shows info about the project and there is a button called video there that I want to load the video when clicked. This is the code I have for unwrapping the object and showing the info. Some help with this would be much appreciated!
#IBOutlet weak var videoView: UIView!
#IBOutlet weak var videoStatus: UILabel!
#IBOutlet weak var productVideo: UIButton!
#IBOutlet weak var productCategory: UILabel!
#IBOutlet weak var ProductImage: PFImageView!
#IBOutlet weak var productName: UILabel!
#IBOutlet weak var productDescription: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Unwrap the current object object
if let object = currentObject {
productName.text = object["ProductName"] as? String
productDescription.text = object["ProductDescription"] as! String
productCategory.text = object["ProductCategory"] as? String
videoStatus.text = object["VideoStatus"] as? String
var initialThumbnail = UIImage(named: "question")
ProductImage.image? = initialThumbnail!
if let thumbnail = object["ProductImage"] as? PFFile {
ProductImage.file = thumbnail
ProductImage.loadInBackground()
if self.videoStatus.text == "None"
{
self.productVideo.hidden = true
self.videoView.hidden = true
}
}
}
}
vvvThis is in the Tableview controller..^^^^the code above is from the productViewController
//override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! CustomCell!
if cell == nil {
cell = CustomCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
}
// Extract values from the PFObject to display in the table cell
if let ProductName = object?["ProductName"] as? String {
cell.ProductName.text = ProductName
}
// Display product image
var initialThumbnail = UIImage(named: "question")
cell.ProductImage.image? = initialThumbnail!
if let thumbnail = object?["ProductImage"] as? PFFile {
cell.ProductImage.file = thumbnail
cell.ProductImage.loadInBackground()
}
return cell
}
Added this to the viewcontroller
#IBAction func productVideo2(sender: AnyObject) {
let videoWebView = UIWebView(frame: CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height))
let url = object["ProductVideo"] as! String // GET THIS FROM YOUR PARSE OBJECT
let urlRequest = NSURLRequest(URL: NSURL(string: url)!)
videoWebView.loadRequest(urlRequest)
self.view.addSubview(videoWebView)
}
Based on your code, it would be done like this:
override func viewDidLoad() {
super.viewDidLoad()
// Unwrap the current object object
if let object = currentObject {
productName.text = object["ProductName"] as? String
productDescription.text = object["ProductDescription"] as! String
productCategory.text = object["ProductCategory"] as? String
videoStatus.text = object["VideoStatus"] as? String
var initialThumbnail = UIImage(named: "question")
ProductImage.image? = initialThumbnail!
if let thumbnail = object["ProductImage"] as? PFFile {
ProductImage.file = thumbnail
ProductImage.loadInBackground()
if self.videoStatus.text == "None"
{
self.productVideo.hidden = true
self.videoView.hidden = true
} else {
let videoWebView = UIWebView(frame: CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height))
let url = object["ProductVideo"] as! String // GET THIS FROM YOUR PARSE OBJECT
let urlRequest = NSURLRequest(URL: NSURL(string: url)!)
videoWebView.loadRequest(urlRequest)
self.view.addSubview(videoWebView)
}
}
}
}
Update
To use this as you intend you'll need to create a custom UIButton subclass with a property to hold the video Url that's present in your cellForRowAtIndexPath method
Storyboard
Notice the custom UITableViewCell and custom UIButton class assignments in the class inspector on the right.
UIButton Subclass Example
import UIKit
class MyCustomButton: UIButton {
var videoUrl = ""
}
UITableViewCell Subclass Example
import UIKit
class MyCustomTableViewCell: UITableViewCell {
#IBOutlet weak var cellBttn: MyCustomButton!
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
}
}
View Controller Example
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
//MARK: - ivars
var myData = ["One","Two","Three","Four","Five"] // Really just where your video URL is in your code
//MARK: - Overrides
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
//MARK: - UITableViewMethods
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! MyCustomTableViewCell
cell.cellBttn.videoUrl = myData[indexPath.row]
cell.cellBttn.addTarget(self, action: Selector("cellBttnTouched:"), forControlEvents: UIControlEvents.TouchUpInside)
return cell
}
//MARK: - Actions
func cellBttnTouched(sender: MyCustomButton) {
// Spawn your UIWebView here, you can get current video URL from the sender
let thisCellsVideoUrl = sender.videoUrl
println(thisCellsVideoUrl)
}
}
This example products this output when the button is tapped:

Resources