Custom delegate is always nil - swift3

I have a problem with my delegate use in a protocol, many person face the same problem but no answer works for me.
My first class is FavorisHeaderTableView
import UIKit
protocol FavorisHeaderDelegate {
func changeFavoris(sender: FavorisHeaderTableViewCell)
}
class FavorisHeaderTableViewCell: UITableViewCell {
#IBOutlet weak var lblTitle: UILabel!
#IBOutlet weak var txtFavoriteNameInput: UITextField!
#IBOutlet weak var lblIcon: UILabel!
#IBOutlet weak var lblTime: UILabel!
#IBOutlet weak var lblDescription: UILabel!
#IBOutlet weak var btnFavHeart: UIButton!
#IBOutlet weak var btnFavHome: UIButton!
#IBOutlet weak var btnFavShop: UIButton!
#IBOutlet weak var btnFavWork: UIButton!
#IBOutlet weak var btnFavGolf: UIButton!
var myDelegate: FavorisHeaderDelegate? = nil
var defaultIcon:FavIconType = .heart
var selectedIcon:UIButton? = nil {
didSet {
selectedIcon!.backgroundColor = Design.Palette.red
selectedIcon?.layer.cornerRadius = 3
selectedIcon?.tintColor = Design.Palette.white
}
willSet {
if selectedIcon != nil {
selectedIcon!.backgroundColor = UIColor.clear
selectedIcon?.tintColor = UIColor(red:0.671, green:0.651, blue:0.635, alpha:1)
}
}
}
#IBAction func didSelectIcon(_ sender: UIButton) {
selectedIcon = sender
self.myDelegate?.changeFavoris(sender: self)
}
#IBAction func changeTitle(_ sender: Any) {
txtFavoriteNameInput.text = "gare centro"
print("delegate: ",myDelegate)
if myDelegate != nil {
myDelegate?.changeFavoris(sender: self)
}
}
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
}
}
The second class who use the protocol is
addFavoriteViewController: UIViewController {
// MARK properties
let defaultLocalizer = AMPLocalizeUtils.defaultLocalizer
var favorisName:String? = nil
var defaultIcon:FavIconType = .heart
var delegate:handleFavorite? = nil
#IBOutlet weak var favTableView: UITableView!
var headerCell:FavorisHeaderTableViewCell?
override func viewDidLoad() {
super.viewDidLoad()
// Localization of labels
//lblAddToFavorite.text = defaultLocalizer.stringForKey(key: "str_favorites_addTitle")
//lblFavoriteName.text = defaultLocalizer.stringForKey(key: "str_favorites_nameInput")
favTableView.delegate = self
favTableView.dataSource = self
self.headerCell?.myDelegate = self
}
override func viewWillAppear(_ animated: Bool) {
// Text Field
//favorisName.clearButtonMode = .whileEditing
}
var place:PlaceModel? = nil
var itinerary:(source:PlaceModel, destination:PlaceModel)? = nil
let db = DataController.shared
var favorite:FavoritesMO? = nil
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension UGOaddFavoriteViewController: FavorisHeaderDelegate {
func changeFavoris(sender: FavorisHeaderTableViewCell) {
defaultIcon = sender.defaultIcon
favorisName = sender.txtFavoriteNameInput.text
}
}
When I try this code "myDelegate" is always nil and I don't understand what's wrong despite of all topic read about this problem.

You are setting self as the delegate of the wrong cell!
Here:
self.headerCell?.myDelegate = self
you set the headerCell's delegate to self, but headerCell is never actually displayed on the screen!
You need to actually set the delegates of the cells on the screen, not the delegate of a random cell that you created.
The best place to do this is cellForRowAtIndexPath:
let cell = tableView.dequeueResusableCell(withIdentifier:...)!
// configure your cell
cell.delegate = self // set the delegate here!

Related

How to save the google Placepicker locations to tableviewcell?

I have written this code, i want the picker location to be saved to tableview cells every time i pick the place from place picker.
As of now only one place, i am able to save. I have tried searching in google and other things didn't get correct one. Can anyone help me with this.
class SetLocationLocationsVC: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
#IBOutlet weak var setLocationImagePin: UIImageView!
#IBOutlet weak var ClearLabel: UILabel!
#IBOutlet weak var DeleteButton: UIButton!
#IBOutlet weak var SetLocationView: UIView!
#IBOutlet weak var PickUpLocationButton: UIButton!
#IBOutlet weak var AddressTextField: UITextField!
#IBOutlet weak var LocationButton: UIButton!
#IBOutlet weak var NameLabel: UILabel!
#IBOutlet weak var tableViewForLocations: UITableView!
var placesClient: GMSPlacesClient!
override func viewDidLoad() {
super.viewDidLoad()
placesClient = GMSPlacesClient.shared()
AddressTextField.isHidden = true
tableViewForLocations.delegate = self
tableViewForLocations.dataSource = self
AddressTextField.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
#IBAction func PickPlace(_ sender: Any) {
let center = CLLocationCoordinate2D(latitude: 37.788204, longitude: -122.411937)
let northEast = CLLocationCoordinate2D(latitude: center.latitude + 0.001, longitude: center.longitude + 0.001)
let southWest = CLLocationCoordinate2D(latitude: center.latitude - 0.001, longitude: center.longitude - 0.001)
let viewport = GMSCoordinateBounds(coordinate: northEast, coordinate: southWest)
let config = GMSPlacePickerConfig(viewport: viewport)
let placePicker = GMSPlacePicker(config: config)
AddressTextField.isHidden = false
placePicker.pickPlace(callback: {(place, error) -> Void in
if let error = error {
print("Pick Place error: \(error.localizedDescription)")
return
}
if let place = place {
self.NameLabel.text = place.formattedAddress?.components(separatedBy: ", ")
.joined(separator: "\n")
} else {
self.NameLabel.text = ""
}
})
}
#IBAction func SetLocationClicked(_ sender: Any) {
tableViewForLocations.reloadData()
AddressTextField.isHidden = true
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableViewForLocations.dequeueReusableCell(withIdentifier: "mycell", for: indexPath) as! LocationCell
cell.Label1.text = AddressTextField.text
cell.Label2.text = NameLabel.text
tableViewForLocations.register(UITableViewCell.self, forCellReuseIdentifier: "mycell")
return cell
}
#IBAction func DeleteClicked(_ sender: Any) {
}
}

IBOutlet with arc4random in swift3.0

i have code
class ViewController: UIViewController {
var detailText: String = "Chance of win is 50%"
#IBOutlet weak var winChance: UILabel!
func someMethod () -> Void {
print("Method called!")
}
override func viewDidLoad() {
super.viewDidLoad()
self.winChance.text = self.detailText
} }
how can i make arc4random for this 50%??
if i used something with "(var)" it is not help me
Thnx
Try this
class ViewController: UIViewController {
#IBOutlet weak var winChance: UILabel!
func someMethod () -> Void {
print("Method called!")
}
override func viewDidLoad() {
super.viewDidLoad()
let randomNumber = Int(arc4random_uniform(100))
self.winChance.text = "Chance of win is \(randomNumber)%"
}
}

IOS 10 - Swift 3.0: Stop the delegated function to save the image

I'm making an App with swift 3, xCode 8.2 and IOS10. The interface has a thermal vision screen (FLIR ONE). My question is, how can I take a photo? My code is:
import UIKit
class ThermalCameraVC: UIViewController, FLIROneSDKImageReceiverDelegate, FLIROneSDKStreamManagerDelegate {
//MARK: OUTLETS
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var labelStatusCamera: UITextField!
#IBOutlet weak var labelCargeCamera: UITextField!
#IBOutlet weak var icnCancelPicture: UIButton!
#IBOutlet weak var icnUploadPicture: UIButton!
#IBOutlet weak var iconTakePicture: UIButton!
//MARK: VARIABLES
var simulatorStatus = false
var cameraBussy = false
override func viewDidLoad() {
super.viewDidLoad()
FLIROneSDKStreamManager.sharedInstance().addDelegate(self)
FLIROneSDKStreamManager.sharedInstance().imageOptions = FLIROneSDKImageOptions(rawValue: FLIROneSDKImageOptions.blendedMSXRGBA8888Image.rawValue)!
icnCancelPicture.isHidden = true
icnUploadPicture.isHidden = true
}
//MARK: CANCEL PICTURE
#IBAction func cancelPicture(_ sender: Any) {
cameraBussy = false
}
//MARK: UPLOAD PICTURE AMAZON S3
#IBAction func uploadPicture(_ sender: Any) {
}
func flirOneSDKDelegateManager(_ delegateManager: FLIROneSDKDelegateManager!, didReceiveBlendedMSXRGBA8888Image msxImage: Data!, imageSize size: CGSize){
let image = FLIROneSDKUIImage(format: FLIROneSDKImageOptions.blendedMSXRGBA8888Image, andData: msxImage, andSize: size)
//HERE I NEED TO STOP THE DELEGATED FUNCTION TO SAVE THE IMAGE !!
if self.cameraBussy{
//cameraBussy = false
}else{
DispatchQueue.main.async{
self.imageView.image = image
}
}
}
#IBAction func takeThermalPicture(_ sender: Any) {
cameraBussy = true
icnCancelPicture.isHidden = false
icnUploadPicture.isHidden = false
iconTakePicture.isHidden = true
}
}
How can I stop the flow of data in this delegated function? Because it is continually calling.
Set the delegate value to nil.
#IBAction func takeThermalPicture(_ sender: Any) {
FLIROneSDKStreamManager.sharedInstance().addDelegate(nil)
cameraBussy = true
icnCancelPicture.isHidden = false
icnUploadPicture.isHidden = false
iconTakePicture.isHidden = true
}

update progress view download within custom table view cell in swift language

i have an question about how can i update my progress view in my custom table view cell which is download file from the internet ? if i reload the table view it take huge memory and increasing the memory
tableView.reloadData()
also if i reload the only one section it also take huge memory and increase memory
tableView.reloadSections([0], with: .none)
so please what is the best way to update progress view within my custom table view cell?
the following my custom table view class :
import UIKit
class DownloadingTableViewCell: UITableViewCell {
#IBOutlet weak var movieDeleteButton: UIButton!
#IBOutlet weak var movieImageView: UIImageView!
#IBOutlet weak var movieNameLabel: UILabel!
#IBOutlet weak var movieProgreesView: UIProgressView!
#IBOutlet weak var movieSizeLabel: UILabel!
weak var movieObject:DownloadVideo? {
didSet {
updateUI()
}
}
func updateUI() {
movieImageView.image = nil
movieNameLabel.text = nil
movieSizeLabel.text = nil
movieProgreesView.progress = 0.0
if let movieObject = movieObject {
movieImageView.image = UIImage(named: "movie")
movieNameLabel.text = movieObject.videoName
// set the label size file
if movieObject.totalData != nil {
let totalSize = ByteCountFormatter.string(fromByteCount:movieObject.totalData!, countStyle: .binary)
movieSizeLabel.text = String(format: "%.1f%% of %#", (movieObject.data)! * 100 ,totalSize)
}
/////////////////////////
if let movieData = movieObject.data {
movieProgreesView.progress = movieData
}
}// end the fetch object
}
}
thanks a lot
You should add a parameter in your data source related to file downloading progress and update progress in main thread
if let movieData = movieObject.data {
dispatch_get_main_queue().asynchronously() {
movieProgreesView.progress = movieData
}
}

the table view cells not release from memory

i hope all is well
i have an issue with cell in table view it's not releasing when i scrolling in table view the following is my code
class MovieDownloadedTableViewCell: UITableViewCell {
#IBOutlet weak var movieImageView: UIImageView!
#IBOutlet weak var movieNameLabel: UILabel!
#IBOutlet weak var movieEmptyCircleImageView: UIImageView!
#IBOutlet weak var movieCheckMarkImageView: UIImageView!
var fetchURL:URL? {
didSet {
updateUI()
}
}
func updateUI() {
movieImageView.image = nil
movieNameLabel.text = nil
movieEmptyCircleImageView.isHidden = true
movieCheckMarkImageView.isHidden = true
if let fetchURL = fetchURL {
if fetchURL.pathExtension == "" {
movieImageView.image = UIImage(named: "folder")
}else{
movieImageView.image = UIImage(named: "movie")
}
movieNameLabel.text = fetchURL.lastPathComponent
}// end the if let
}// end the func updateUI
}// end the class
the above my custom table view cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as? MovieDownloadedTableViewCell
// defining the cell
if let cell = cell {
cell.tintColor = UIColor.white
cell.fetchURL = operationDocumentDirectoryObject.arrayOfMovieURL?[indexPath.row]
if isShowToolBar {
if operationDocumentDirectoryObject?.arrayOfShowAllEmptyCircle?[indexPath.row] == indexPath.row {
cell.movieEmptyCircleImageView.isHidden = false
}// end the if
if operationDocumentDirectoryObject.dictionaryHoldIndexCellForDisplayWhichCellSelected.count > 0 {
if operationDocumentDirectoryObject.dictionaryHoldIndexCellForDisplayWhichCellSelected[indexPath.row] == indexPath.row {
cell.movieEmptyCircleImageView.isHidden = true
cell.movieCheckMarkImageView.isHidden = false
}
}
}// end if for the isShowVar
}// end the creating cell
return cell!
}
please where my wrong code how can i make my table view cell when i scrolling is releasing from memory every time
thank you very much