Swift Update Label (With HTML Content) Takes 1Min

Swift Update Label (with HTML content) takes 1min

Usual problem of updating UI in a secondary thread:

Your closure is obviously not running on the main thread, as the URL task is asynchronous. So updating the label on the closure will have to wait for the main thread to run its update loop. The way to fix it is to wrap the .text = call to force it to run on the main thread (which is where the UI stuff should run anyway):

        dispatch_async(dispatch_get_main_queue()) {
self.LBoutput.text = "test6"
}

UILabel doesn't update after button click

Your displayButtonAction is in fact nil. Notice in your method addButtonAndLabels() you are creating a label and populating the text only within the scope of that method here:

let displayButtonAction = makeALabel(yLabelStart: viewElementVerticalLocation, underSubview: getNextorkImplementation)

In your makeALabel method, you are inserting that label as a subview of your view which is why it shows up when you run the application. Nowhere are you assigning that label to displayButtonAction.

In summary, You are creating a local scope UILabel, populating it's placeholder text, inserting it as a subview of your view, then discarding it, then trying to populate the text of your displayButtonAction label on button press of which is nil.

Within addButtonAndLabels(), assigning the instantiated label to your main label in the main scope of the view controller via:

self.displayButtonAction = displayButtonAction

will get you started in the right direction.

Using the debugger tools, breakpoints, and po are your friends in situations like these.

update text field ui in swift ios

Same issue that everyone is having when wanting to do UI updates in Swift: do not ever update the UI in any secondary thread. And that means anything with closures. Since Swift is using closures so much, that issue is being seen a lot more but it isn't new.

See Swift Update Label (with HTML content) takes 1min for the correct way of doing things.

Update View every day

Simpler solution: Save only the day integer and add an observer to be notified when the day changes

override func viewDidLoad() {
super.viewDidLoad()
let today = Calendar.current.component(.day, from: Date())
let lastRe = UserDefaults.standard.integer(forKey: "lastRe")
if today != lastRe {
updateView(day: today)
}
}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(forName: .NSCalendarDayChanged, object:nil, queue: .main) { [weak self] _ in
let today = Calendar.current.component(.day, from: Date())
self?.updateView(day: today)
}
}

override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(self, name:.NSCalendarDayChanged, object:nil)
}

func updateView(day : Int) {
nextDay()
UserDefaults.standard.set(day, forKey: "lastRe")
}

Swift map issue

Pointer Explanation

What’s happening here is you’re hitting an implicit conversion of arrays to pointers, that is there for C compatibility purposes.

Ordinarily, you wouldn’t be able to add 1 to an array. I mean, what would it mean to do that? However, Swift does have an implicit conversion of arrays to pointers, so that you can pass arrays into C functions:

import Darwin
// prints out “hello” using a standard C function that takes a char*
puts([104,101,108,108,111,0])

And you can add integers to pointers (to do good ol’ pointer arithmetic):

// x will be an UnsafePointer<Int>
let x = [1,2,3] + 1

Now, to stop you doing this by accident, this is only supposed to work on literals:

let a = [104,101,108,108,111,0]
// error: binary operator '+' cannot be applied to operands of type '[Int]' and 'Int'
let x = a + 1

But when using generic functions, this conversion still happens (possibly unintentionally).

Issues with your Map

It looks from your definition like you’re trying to write a version of map for optionals – that is, something that takes an optional, and maps the contents if it has some.

But then, instead of mapping optionals, you’re using it to on sequences. In fact in your code snippet, on the line let test2 = map(test1, { $0 + 1 }), you aren’t calling your map at all – you’re calling the standard library version that takes a sequence (and returns an array). Try putting an assert(false) in there – you’ll see it’s not being called the first time around.

Map for optionals and map for arrays are very conceptually similar. This is because optionals and arrays are both “functors” – the name for things that can be “mapped over”. Think of them both as containers – types that contain other types. In the case of optionals, they contain a value or not. In the case of arrays, they contain any number of values. But in both cases, it’s useful to have a function that you apply to the “contents” while leaving them within the “container”.

Consider the following code. It has two maps, for sequences and optionals, and applys them in turn. The last example seems to be what you were looking for in your question’s last case – mapping plus-one on each member of an array of optionals. This is really two maps, one within the other.

func mymap<A, B>(x: A?, transform: A -> B) -> B? {
println("map for optionals called!")
if let x1 = x {
return transform(x1)
}
return nil
}

func mymap<S: SequenceType, T>(source: S, transform: S.Generator.Element -> T) -> [T] {
println("map for sequences called!")
var result: [T] = []
for x in source {
result.append(transform(x))
}
return result
}

let test1 = [1, 2, 3, 4]
// prints "map for sequences called!"
let test2 = mymap(test1, { $0 + 1 })
println(test2) // prints

let test3: Int? = 5
// prints "map for optionals called!"
let test4 = mymap(test3, { $0 + 1 })
println(test4) // Optional(6)

let test5: [Int?] = [1, nil, 3, 4]
// prints "sequences called" followed by 4 "optionals called"
let test6 = mymap(test5) { mymap($0) { i in i + 1 } }
println(test6) // [Optional(2), nil, Optional(4), Optional(5)]

How can I make a countdown with NSTimer?

Question 1:

@IBOutlet var countDownLabel: UILabel!

var count = 10

override func viewDidLoad() {
super.viewDidLoad()

var timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(UIMenuController.update), userInfo: nil, repeats: true)
}

func update() {
if(count > 0) {
countDownLabel.text = String(count--)
}
}

Question 2:

You can do both. SpriteKit is the SDK you use for scene, motion, etc. Simple View Application is the project template. They should not conflict

presses not working tvos - swift

I have found the answer, but I am not sure why the override method didn't work.

let press:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(pressed))
press.allowedPressTypes = [NSNumber(value: UIPressType.select.rawValue)]
view.addGestureRecognizer(press)

Custom sorting in Swift

I'm not sure that this algorithm catches all cases but at least that one in the question.

let refNum : Int64 = 50

let sortedArray = testArr.sort { (rangeA, rangeB) -> Bool in
let a = (rangeA.start...rangeA.end).contains(refNum)
let b = (rangeB.start...rangeB.end).contains(refNum)

switch (a, b) {
case (true, true), (false, false) : return rangeA.start < rangeB.start
case (true, false) : return true
case (false, true) : return false
}
}

print(sortedArray)

xpath to get checkbox inside label

Your expression is failing because your label has more that one text node: an empty string before the input, and Test3. The way you're using contains means it will only check the first text node, ie empty string.

Two ways of solving this:

  • eliminating the empty strings with normalize-space():

    //*[contains(text()[normalize-space()], 'Test3')]
  • querying each text():

    //*[text()[contains(.,'Test3')]]

For a more detailed explanation, see How to search for content in XPath in multiline text using Python?.



Related Topics



Leave a reply



Submit