Can someone please explain, what I should add to code to display in UILabel which number was taken as random from image?
Here's my code:
#IBOutlet weak var diceImageView1: UIImageView!
#IBOutlet weak var diceImageView2: UIImageView!
#IBOutlet weak var Label: UILabel!
#IBAction func rollButtonPressed(_ sender: UIButton) {
let diceArray = [ #imageLiteral(resourceName: "DiceOne"),#imageLiteral(resourceName: "DiceTwo"),#imageLiteral(resourceName: "DiceThree"),#imageLiteral(resourceName: "DiceFour"),#imageLiteral(resourceName: "DiceFive"),#imageLiteral(resourceName: "DiceSix") ]
diceImageView1.image = diceArray.randomElement()
diceImageView2.image = diceArray.randomElement()
Label.text = (diceImageView1.image)
}
Here's error I'm getting:
Cannot assign value of type 'UIImage?' to type 'String?'
Thank you!
Related
I've tried to get it to work like so:
class CalendarViewController: DayViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "CalendarKit Demo"
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Dark",
style: .done,
target: self,
action: #selector(changeStyle))
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Change Date",
style: .plain,
target: self,
action: #selector(presentDatePicker))
navigationController?.navigationBar.isTranslucent = false
dayView.autoScrollToFirstEvent = true
reloadData()
}
#objc func changeStyle() {
print("clicked change style")
}
#objc func presentDatePicker() {
print("clicked date picker")
}
override func eventsForDate(_ date: Date) -> [EventDescriptor] {
let models = [Happening(startDate: Date(), endDate: Date(timeInterval: 3600, since: Date()), title: "Test Event", location: "on mother earth")]
var events = [Event]()
for model in models {
let event = Event()
event.startDate = model.startDate
event.endDate = model.endDate
let info = [model.title, model.location]
event.text = info.reduce("", {$0 + $1 + "\n"})
events.append(event)
}
return events
}
}
struct Happening {
let startDate: Date
let endDate: Date
let title: String
let location: String
init (startDate: Date, endDate: Date, title: String, location: String) {
self.startDate = startDate
self.endDate = endDate
self.title = title
self.location = location
}
}
Calendar shows up but I'm neither getting a title nor navigation items.
Looks like this for me:
What am I doing wrong here?
Many thanks for your help!
Question on the side:
Didn't yet figure out how (or if possible at all) to work with it in interface builder, to e.g. add a custom navigation element at the top when integrating it into another app. Is that possible?
starting from the last question: the Interface Builder is not currently supported. I recommend creating your CalendarController in code. Some features might work with the Interface Builder, although their support is not guaranteed.
The missing link is that the CalendarController is not embedded inside an instance of the UINavigationController. You can do so in your AppDelegate.swift or SceneDelegate.swift file:
import UIKit
import CalendarKit
#UIApplicationMain
final class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.backgroundColor = UIColor.white
window?.makeKeyAndVisible()
let dayViewController = CalendarViewController() // Create a view controller
// Now create a NavigationController with CalendarController embedded inside
let navigationController = UINavigationController(rootViewController: dayViewController)
window?.rootViewController = navigationController
return true
}
}
Let me know, if this helps you integrate the CalendarKit. Also, I'd appreciate having a reproducible test project, so that I could investigate the problem myself.
I have a situation where a string returned from a function call is being assigned to a UILabel text. However, the UILabel is carrying an empty value. If I were to assign a static string viz. "this is testing" to the UILabel directly it works. Within the function, I can print the return value
import Foundation
import Firebase
import UIKit
class checkLocation{
var items = [addedItems]()
func getLocationOfItem(textFieldText: (String)) -> String{
let itemLet = addedItems()
var location = ""
Database.database().reference().child("item").observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject]{
//itemLet.setValuesForKeys(dictionary)
itemLet.itemName = dictionary["itemName"] as? String
itemLet.itemLocation = dictionary["itemLocation"] as? String
itemLet.itemImageUrl = dictionary["itemImageUrl"] as? String
itemLet.itemTS = dictionary["itemTS"] as? String
itemLet.id = dictionary["id"] as? String
if(textFieldText == itemLet.itemName){
location = itemLet.itemLocation!
print(location)
}
}
}, withCancel: nil)
return location
}
}
Calling program
import UIKit
import Firebase
class checkLocationViewController: ViewController {
#IBOutlet weak var itemNameInLctn: UITextField!
#IBOutlet weak var itemLocationLbl: UILabel!
var items = [addedItems]()
var strLocation = "";
override func viewDidLoad() {
super.viewDidLoad()
refItems = Database.database().reference().child("item")
}
#IBAction func getLocation(_ sender: UIButton) {
self.strLocation = checkLocation().getLocationOfItem(textFieldText: itemNameInLctn.text!)
itemLocationLbl.text = strLocation
//itemLocationLbl.text = strLocation
//print(itemNameInLctn.text)
}
}
Any help?
The func getLocationOfItem(textFieldText: (String)) -> String is correctly returning location that has the initial value of "“.
The issue that you are facing is that, you are calling an an async task from firebase within a sync function call.
You can refactor the method call to return you the required string asynchronously be making the following changes:
func getLocationOfItem(textFieldText: String, completion: #escaping (_ itemLocation: String?) -> Void){
let itemLet = addedItems()
Database.database().reference().child("item").observe(.childAdded, with: { (snapshot) in
guard let dictionary = snapshot.value as? [String: AnyObject] else {
return completion(nil)
}
itemLet.itemName = dictionary["itemName"] as? String
itemLet.itemLocation = dictionary["itemLocation"] as? String
itemLet.itemImageUrl = dictionary["itemImageUrl"] as? String
itemLet.itemTS = dictionary["itemTS"] as? String
itemLet.id = dictionary["id"] as? String
if(textFieldText == itemLet.itemName){
completion(itemLet.itemLocation)
} else {
completion(nil)
}
}, withCancel: nil)
}
/// Usage
#IBAction func getLocation(_ sender: UIButton) {
guard let itemNameInLocation = itemNameInLctn.text else { return }
getLocationOfItem(textFieldText: itemNameInLocation) { [weak self] (itemLocation) in
self?.strLocation = itemLocation
self?.itemLocationLbl.text = itemLocation
}
}
Note:
Please be advised that the completion handler will be called every time that a value is added under the item path in your firebase database.
I would highly recommend refactoring further in this case to use the observeSingleEventthat firebase provides.
Please see link below for documentation about said method:
https://firebase.google.com/docs/database/ios/read-and-write#read_data_once
If this was your intention then its the best choice.
I feel like I'm missing a basic step with this code set and really would appreciate any insight since I couldn't find a great solution despite searching these forums.
I have four textfields, two UI buttons, and two labels.
When the first three textfields have input, one of the UI buttons should be enabled allowing me to calculate the sum of those three textfields and display it on the first label.
The second UI button should only be enabled if the fourth textfield has input. The second label will contain the sum of all four textfields. If these conditions aren't met, the UI buttons should be disabled.
I have the first situation working great, but things get messed up when I try to incorporate the fourth text field and second button. See the last snippet: let regurgVTI = AIVTI.text, !regurgVTI.isEmpty
class AICalc: UIViewController
{
#IBOutlet weak var PISARadius: UITextField!
#IBOutlet weak var aliasingVelocity: UITextField!
#IBOutlet weak var AIVMax: UITextField!
#IBOutlet weak var AIVTI: UITextField!
#IBOutlet weak var EROAAnswer: UILabel!
#IBOutlet weak var RegurgVolumeAnswer: UILabel!
#IBOutlet weak var calcEROAButton: UIButton!
#IBOutlet weak var regurgVolumeButton: UIButton!
#IBAction func calcEROA(_ sender: UIButton)
{
EROAAnswer.text = String(Int(PISARadius.text!)! + Int(aliasingVelocity.text!)! + Int(AIVMax.text!)!)
}
#IBAction func calcRegurgVolume(_ sender: UIButton)
{
RegurgVolumeAnswer.text = String(Int(PISARadius.text!)! + Int(aliasingVelocity.text!)! + Int(AIVMax.text!)! + Int(AIVTI.text!)!)
}
override func viewDidLoad()
{
super.viewDidLoad()
calcEROAButton.isEnabled = false
regurgVolumeButton.isEnabled = false
PISARadius.addTarget(self, action: #selector(editingChanged(_:)), for: .editingChanged)
aliasingVelocity.addTarget(self, action: #selector(editingChanged(_:)), for: .editingChanged)
AIVMax.addTarget(self, action: #selector(editingChanged(_:)), for: .editingChanged)
AIVTI.addTarget(self, action: #selector(editingChanged(_:)), for: .editingChanged)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#objc func editingChanged(_ textField: UITextField) {
if textField.text?.count == 1 {
if textField.text?.first == " " {
textField.text = ""
return
}
}
guard
let pisa = PISARadius.text, !pisa.isEmpty,
let aliasing = aliasingVelocity.text, !aliasing.isEmpty,
let vmax = AIVMax.text, !vmax.isEmpty
else {
calcEROAButton.isEnabled = false
regurgVolumeButton.isEnabled = false
return
}
calcEROAButton.isEnabled = true
let regurgVTI = AIVTI.text, !regurgVTI.isEmpty
}
}
Use textField.tag or textField.identifier to identify textfield then you can solve your problem easily.
Let say your 1st three textfields have tag 1,2,3 simultaneously.
Then in your textfield did end_Enditing :-
if textfield.tag == 1 {
//Do whatever you want
}
if textfield.tag == 2 {
//Do whatever you want
}
if textfield.tag == 3 {
//Do whatever you want
}
Referring this may solve your problem.
Best luck.
I tried to make sum but its keep telling me that I can't sum int to a string , whats wrong with my code ?!
I need to put a number in a textfield then I put another number to be sum in the label , so I need to take the number in the label and sum with the new entry , Am I right ?
#IBOutlet weak var oursResult: UILabel!
#IBOutlet weak var theirsResult: UILabel!
#IBOutlet weak var note: UILabel!
#IBOutlet weak var oursInput: UITextField!
#IBOutlet weak var theirsInput: UITextField!
#IBAction func calButton(sender: AnyObject) {
var enteredOurs = Int(oursInput.text!)
var enteredTheirs = Int(theirsInput.text!)
if enteredOurs != nil {
if oursResult.text != nil { // my problem starts from here
var firstMove = (oursResult.text! as NSString)
var secondMove = enteredOurs
var sum = firstMove + secondMove
oursResult.text = "\(sum)"
}
oursResult.text = "\(enteredOurs!)"
}else {
note.text = "please enter a number"
}
}
your variable firstMove is NSString..so you can't applied operator to different operands like NSString and Int.
So Just change....
var firstMove = Int(oursResult.text!) // instead of (oursResult.text! as NSString)
var secondMove = enteredOurs
var sum = firstMove + secondMove // Now both variables are Integer
I want to change the dock icon of an app into one big character like an "A" or "B" for example using swift or objective C
import Cocoa
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
#IBOutlet weak var window: NSWindow!
#IBOutlet weak var dockView: NSView!
#IBOutlet weak var dockText: NSTextField!
let appDockTile = NSApplication.sharedApplication().dockTile
func prepareDock(){
appDockTile.contentView = dockView
appDockTile.display()
}
func changeText(){
dockText.stringValue = "B"
appDockTile.display()
}
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
prepareDock()
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
#IBAction func btnChangeText(sender: AnyObject) {
changeText()
}
}
my two cents for OSX swift 4.x:
(make it flash..)
...
self.HeartBeatTimer = Timer.scheduledTimer(withTimeInterval: DELTA_T, repeats: true, block: { (t: Timer) in
let name = colored ? "heartbeat" : "heartbeat_red"
let image = NSImage(named: name)
let appDockTile = NSApplication.shared.dockTile
appDockTile.contentView = NSImageView(image: image!)
appDockTile.display()
}