IBOutlet with arc4random in swift3.0 - swift3

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)%"
}
}

Related

SwiftUI Send SMS with Coordinator and UIViewControllerRepresentable

How can I write the following code with UIViewControllerRepresentable?
I want to use UIViewControllerRepresentable. I want the code I write to be regular. Do you think it makes sense to write this code with UIViewControllerRepresentable?
import MessageUI
class ViewController: UIViewController, MFMessageComposeViewControllerDelegate {
#IBOutlet weak var phoneNumber: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func sendText(sender: UIButton) {
if (MFMessageComposeViewController.canSendText()) {
let controller = MFMessageComposeViewController()
controller.body = "Message Body"
controller.recipients = [phoneNumber.text]
controller.messageComposeDelegate = self
self.presentViewController(controller, animated: true, completion: nil)
}
}
func messageComposeViewController(controller: MFMessageComposeViewController!, didFinishWithResult result: MessageComposeResult) {
//... handle sms screen actions
self.dismissViewControllerAnimated(true, completion: nil)
}
override func viewWillDisappear(animated: Bool) {
self.navigationController?.navigationBarHidden = false
}
}
SMSViewController
struct SMSViewController: UIViewControllerRepresentable {
class Coordinator: NSObject, MFMessageComposeViewControllerDelegate {
func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) {
}
var parent: MFMessageComposeViewController
init(_ parent: MFMessageComposeViewController) {
self.parent = parent
}
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIViewController(context: UIViewControllerRepresentableContext<MFMessageComposeViewController>) -> MFMessageComposeViewController {
let messageViewController = MFMessageComposeViewController()
messageViewController.delegate = context.coordinator
return messageViewController
}
func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
}
}

Custom delegate is always nil

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!

Unlapping optional error in UIView

I wanted to programmatically control the menu view so I tried the following:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var menuView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func menuBtn(_ sender: UIButton) {
print("menuBtn")
print(type(of: menuView!)) // <- `Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)`
}
}
And click the button, console says
fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)
Both are connected to ViewController.
How can I get print(type(of: menuView!))?
===============================================================
ps.
I've simplified my real problem. this is my real code:
button on ViewController.Swift
#IBAction func openModal(_ sender: UIButton) {
print("open btn clicked")
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "menuViewController") as! MenuViewController
self.addChildViewController(vc)
self.view.addSubview(vc.contentView!) /// <- This cause problem
}
MenuViewController.swift
import UIKit
class MenuViewController: UIViewController {
#IBOutlet weak var contentView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.clear
view.isOpaque = false
}
#IBAction func closeBtn(_ sender: UIButton) {
print("close btn clicked")
self.view.removeFromSuperview()
}
}
and Why I wan't using it:
I can't scrolling when menuView appeared.. I want to use the buttons in the menu view and scroll at the same time.

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

Passing an array using protocols/delegates

I have tried over and over to get this to work, but to no avail. I am trying to pass an array from a SendingVC to a ReceivingVC and display the content of that array in two labels.
SendingVC Code:
import UIKit
protocol SenderVCDelegate {
func passArrayData(data: [String])
}
class SendingVC: UIViewController {
// DELEGATE
var delegate: SenderVCDelegate?
var carDetails: [String]? = ["BMW", "X5"]
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func unwindToFirst(segue: UIStoryboardSegue) {
//
}
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
if (carDetails?.isEmpty)! {
return false
} else {
if let delegate = delegate, let data = carDetails {
delegate.passArrayData(data: data)
print("from inside segue: \(data)")
}
return true
}
}
}
ReceivingVC Code
import UIKit
class ReceivingVC: UIViewController, SenderVCDelegate {
#IBOutlet weak var lbl01: UILabel!
#IBOutlet weak var lbl02: UILabel!
var incomingCarDetails: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
print("from inside viewLoad: \(incomingCarDetails)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?){
if let sendingVC: SendingVC = segue.destination as? SendingVC {
sendingVC.delegate = self
}
}
func passArrayData(data: [String]) {
incomingCarDetails = data
populateLabels(array: incomingCarDetails)
}
func populateLabels(array: [String]) {
for (index, value) in array.enumerated() {
switch index {
case 0:
lbl01.text = value
case 1:
lbl02.text = value
default:
break
}
}
}
}
Any help would be appreciated! :)
Thanks!
You seem to have confusion around the role of a delegate and where it should be implemented. You don't need to use a delegate to pass data from SendingVC to RecevingVC, you can simply set the property on the destination view controller in prepareForSegue;
class SendingVC: UIViewController {
func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destVC = segue.destinationViewController as? ReceivingVC {
destVC.incomingCarDetails = self.carDetails
}
}
}
If you do want to use a delegate, then you will set the SendingVC instance as the delegate of your ReceivingVC in prepareForSegue and change your protocol so that the delegate method returns data, rather than accepts data:
protocol SenderVCDelegate {
func passArrayData() -> [String]
}
Then, you can implement the delegate method and set the delegate in prepareForSegue
class SendingVC: UIViewController, SenderVCDelegate {
func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destVC = segue.destinationViewController as? ReceivingVC {
destVC.senderDelegate = self
}
}
func passArrayData() -> [String] {
return self.carDetails
}
}
In ReceivingVC you can call the delegate method in viewWillAppear
class ReceivingVC: UIViewController {
var incomingCarDetails = [String]()
var senderDelegate: SenderVCDelegate?
override func viewWillAppear(animated: bool) {
super.viewWillAppear(animated)
if let incomingDetails = self.senderDelegate?.passArrayData() {
self.incomingCarDetails = incomingDetails
}
}
}
As you can see this is a whole lot more work and no benefit. A delegation pattern is typically used where you want to send data back and where the function call will happen at an unpredictable time, such as in response to a network operation completing or a user interaction.