Store previous value from stepper in swift - swift

The logic from here Stepper value reset after loaded from coredate doesn't work with me plus its in obj C.
I have a label and stepper, i need the value in the label to act as a counter almost. Currently, when i close and reopen the views the core data works and the value from before shows in the label, but when i tap the stepper (after coming back to the view with the stepper) the value in the label counts from 0 again, i need it to add on to the previous value!
This must be easy but i can't seem to figure it out!
Thanks for any help in advance
#IBAction func stepperTapped(sender: UIStepper) { // when the user taps the stepper
label.text = String(Int(sender.value))
someObject.theCounterProperty = Int(sender.value)
do {
try context!.save()
} catch {
print("error")
}
}

Make sure the label and the counter are up to date when the view reappears. In viewWillAppear set the value from the Core Data object.
label.text = String(someObject.theCounterProperty)
counter.value = Double(someObject.theCounterProperty)

Related

Remember state of cell after animation

Would much appreciate any advice on below.
I'm trying to make my table remember state after animation is completed. Below is my table, when I press button "Invite", animation removes buttons from cell. But during scroll down and back reusableCell draws buttons again.
I decided to use Array in order to remember, which cells were animated, but do not know how not to draw some elements of cell (buttons) during cell creation.
Try this:
Create a boolean variable called animationIsCalled and set it to false.
var animationIsCalled = [Bool](repeating: false, count: numberOfTableViewCells)
#IBAction func buttonPressed(sender: UIButton){
if animationIsCalled{
//Your code is here
}
animationIsCalled[indexPath.row] = false
}
I don't know if your method is an IBAction type or not, but if it is, you can't use indexPath.row. But try to use this boolean variable idea because I've used it before and it's a pretty useful strategy.
Hope this helps.
Alex, thank you a lot for answer! After some experiments the following code worked:
//Create array to remember already animated cells
var sectionTwoSent = [String]()
//Once button tapped append user_id to array above
self.sectionTwoSent.append(self.sectionTwo[indexPath.row].user_id)
//During cell creation, make check and alpha = 0 to hide buttons
for item in sectionTwoSent {
if contact.user_id == item {
cell.inviteButton?.alpha = 0
cell.removeButton?.alpha = 0
cell.invitationDoneLabel?.alpha = 1
break
} else {
cell.inviteButton?.alpha = 1
cell.removeButton?.alpha = 1
cell.invitationDoneLabel?.alpha = 0
}
}

NSMutableAttributedString not rendering correctly

I am using a SplitViewController; The master is tableView with a series of RightDetail cells whose Attributed Strings are set via a callback from a value setting popover.
The value passed back and set via a method that sets the detailTextLabel of the cell. It does this within a DispatchQueue.main.async as some of updates to detailTextLabel are made via calls from Network.Framework
The strange thing is when the popover makes the changes the change to the attributed string is not presented correctly. The focus has to change to the next table cell before the correct drawing occurs.
So it is only when focus changes to "Flow Rate" that temperature is rendered correctly, as shown blow.
I have stepped through the following code and checked that the correct value is being written to self.buttonCell?.detailTextLabel?.attributedText
You'll also see that I've added setNeedsLayout() and setNeedsFocusUpdate()
func setDetailValueWithUnit( to index: Int) {
/** sets the detailtext to the value as the specified index and appends units.
it does this within the main dispatchQueue as this method is called by
operationResult which is called by the statemachine.
**/
DispatchQueue.main.async {
let font = self.buttonCell?.detailTextLabel?.font
let finalString = NSMutableAttributedString(string: valueString,attributes: [.font:font!])
if let units = self.units() {
finalString.append(units)
self.buttonCell?.detailTextLabel?.attributedText = finalString
//next 2 lines experimental in an attempt to fix the attributed text not
//being consistently redendered correctly
self.buttonCell?.detailTextLabel?.setNeedsLayout()
self.buttonCell?.detailTextLabel?.setNeedsFocusUpdate()
NSLog("setDetailValueWithUnit: %d", index)
return
} else {
assert(false, "No Units found")
}
}
}
The problem is that what you are doing is completely wrong. You should never be touching a cell's text label font, text, or anything else directly like that. That's not how a table view works. You should set the table's data model and update the table from there, thus causing cellForRowAt: to be called for the visible cells. In that way, only cellForRowAt: configures the cell, and all will be well.

make NSTableView row stay selected Swift

how would I go about making a previously selectedRow of an NSTableView stay selected after the user presses a button calling a method to work with that selectedRow?
It worked in a previous programm looking like this:
selecting it gives it the OSX selection color, clicking the save button makes the textField becomeFirstResponder() which makes the row go grey automatically and doesnt change the selectedRow property. This is not done by my code, so im happy it just works.
Now in a similar program I want to achieve exactly this, but after clicking a button (calling a method making the textField becomeFirstResponder()) the visual selection is gone and also the tableView property selectedRow goes back to -1 (no row selected).
I tried a lot of ideas, most answers online are objective-C. Here is my most recent code (beeing called by the same button and pretty much faking what worked automatically before):
the NSTableViewAction method and the selectedRowCache variable:
var selectedRowCache = -1
#IBAction func alarmDataTableView(_ sender: NSTableView) {
selectedRowCache = alarmDataTableView.selectedRow
}
the buttonAction:
#IBAction func editAlarmButton(_ sender: NSButton) {
let row = alarmDataTableView.rowView(atRow: self.selectedRowCache, makeIfNecessary: false)
row?.backgroundColor = .blue
}
the selectedRowCache is just a variable that saves the selectedRow whenever the user selects a row (i dont want this).
no with this code the background color of the row doesnt do a thing (besides losing its selection after the button method is called).
the NSTableView is view based.
Thank you for any help!

NSUserDefaults changing every segue

Sorry for the newbie question but i am really stuck.
I have a UIViewController and 4 tableviews in an app. When i click on a button on the UIViewcontroller it segues to a UITableviewController called "Beach". When the user clicks on a cell of the table, it segues back to the UIViewController and displays the selected cells title as the buttons title. The problem that i am having is when i click on a nother button to a tableview and then clicks on the cell, the previous buttons title sets back to the previous title.
i have a prepare for segue function in the tables view controllers and this returns the selected table title (named : Titleoftable) to the main VC which, the strings.
the way i am currently doing it is to make a NSUserDefault below but the problem still remains the same - The value changes top "" every time i click on another table V---
let path = tableView.indexPathForSelectedRow
let cell = tableView.cellForRowAtIndexPath(path!)
let persistenceStoreKey = "MyStringKey"
let stringToStore = "\((cell?.textLabel?.text!)!)"
// Store data
NSUserDefaults.standardUserDefaults().setObject(stringToStore, forKey: persistenceStoreKey)
NSUserDefaults.standardUserDefaults().synchronize()
// Get data
let myStringt = NSUserDefaults.standardUserDefaults().stringForKey(persistenceStoreKey)
destination.textOfBeach = (myStringt)!
destination.isBeachSelected = true
}
I have been stuck on this problem for ages now! PLEASE HELP!!
PS- I am using swift-2 and Xcode7
Make sure that you are not pushing a new ViewController after you click on the tableview's cell. It gives me the impression that it might be the case since you are seeing only the title of the last cell you pressed.. Make sure you actually pop the tableview's controller instead of pushing a new one.
If you want to keep using NSUserDefaults, you could just call
navigationController?.popViewController(animated: true)
in your cellSelection function, and read the defaults value in the viewWillAppear of the main ViewController.
override func viewWillAppear(_ animated: Bool) {
let userDefault = NSUserDefaults.standard()
if let beachSelection = userDefault.string(forKey: "BeachControllerSelection") {
textOfBeach = beachSelection
isBeachSelected = true
}
//same for the rest of the other table view's selections
}

Change text of NSButton in NSTableCellView after click

I have a table of custom NSTableCellViews that contain embedded NSProgressIndicators and NSButtons that I would like to update both immediately after a click, and periodically, on a timer. This is a sample of my code thus far:
func sound(sound: NSSound, didFinishPlaying aBool: Bool) {
pbNowPlaying.doubleValue = sound.currentTime
if aBool == true {
self.btnPlay.stringValue = "Play"
self.btnPlay.state = NSOffState
self.pbNowPlaying.doubleValue = 0
}
self.needsDisplay = true
}
This (and other code where self.needsDisplay = true is set) does not seem to update the view. When I manually reload the table data, the progress bar moves (having been bound to the NSSounds .currentTime value), but the button text/state does not change.
Any advice?
Coding using Swift, Xcode 6.4, OS X 10.10.4
Well, I feel rather dumb, but for anyone else who might be running into the same problem: To modify the text on an NSButton, you need to change the .title property, not the .stringValue property.