how to make sum in one label swift - sum

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

Related

How to display which number was taken as random from image?

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!

Swift: Unable to assign function return value to UILabel

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.

Swift 4 - Enable/Disable Two UI Buttons Based On Different TextField Inputs

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.

Accessing Objective-C Pointers in Swift

I have this Objective-C Code fragment, which I want to express in Swift
CFArrayRef windowList;
AXUIElementCopyAttributeValue(appRef, kAXWindowsAttribute, (CFTypeRef *)&windowList);
if ((!windowList) || CFArrayGetCount(windowList)<1)
continue;
AXUIElementRef windowRef = (AXUIElementRef) CFArrayGetValueAtIndex( windowList, 0);
CFTypeRef role;
AXUIElementCopyAttributeValue(windowRef, kAXRoleAttribute, (CFTypeRef *)&role);
The first thing I´m not sure about: Who allocates the memory behind the windowListPointer.
I tried with this fragment:
var windowListPointer : UnsafeMutablePointer<Optional<AnyObject>>
AXUIElementCopyAttributeValue(appRef, kAXWindowsAttribute as CFString, windowListPointer );
But that does not even compile: It complains, the windowListPointer is not initialised.
What Object I could create, to let the WindowListPointer point to?
If you pass an UnsafeMutablePointer<Optional<AnyObject>> as the last
argument to AXUIElementCopyAttributeValue() then you must
initialize it by allocating (and ultimately releasing) memory:
var resultPtr: UnsafeMutablePointer<Optional<AnyObject>> = UnsafeMutablePointer.allocate(capacity: 1)
resultPtr.initialize(to: nil)
let result = AXUIElementCopyAttributeValue(appRef, kAXWindowsAttribute as CFString, resultPtr)
// ...
resultPtr.deinitialize()
resultPtr.deallocate(capacity: 1)
It is easier
to pass the address of an Optional<AnyObject> variable
with &. Then conditionally
cast the received object to the expected type, in this case an
array of AXUIElement:
var value: AnyObject?
let result = AXUIElementCopyAttributeValue(appRef, kAXWindowsAttribute as CFString, &value)
if result == .success, let windowList = value as? [AXUIElement] {
// use `windowList`
}
and similarly:
if let window = windowList.first {
var value: AnyObject?
let result = AXUIElementCopyAttributeValue(window, kAXRoleAttribute as CFString, &value)
if result == .success, let role = value as? String {
// use `role` ...
}
}
One could define a generic utility function which encapsulates
all the casting:
func axUICopyAttributeValue<T>(of element: AXUIElement, attribute: String, as type: T.Type) -> T? {
var value: AnyObject?
let result = AXUIElementCopyAttributeValue(element, attribute as CFString, &value)
if result == .success, let typedValue = value as? T {
return typedValue
}
return nil
}
Example usage:
if let windowList = axUICopyAttributeValue(of: appRef, attribute: kAXWindowsAttribute, as:[AXUIElement].self) {
for window in windowList {
if let role = axUICopyAttributeValue(of: window, attribute: kAXRoleAttribute, as: String.self) {
// ...
}
}
}
CFArray is the Foundation C version of NSArray (since C doesn't understand Objective C NSObjects). Swift papers over both NSArray and CFArray for you so you don't need to use a pointer; you should just be able to cast it to a Swift array of the appropriate type with as?

how to change dock icon using setContentView to display one big character in mac os x

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