0

I have a register View controller. I have text field for the phone number, and another text field for the country number. i need the country code text field to be on the left and behind it, we should have the phone number. this is working when the app is on English lang, but when the user changes the language to Arabic, we will get the phone number text field on the left not the country code on the left. so, i tried to re-arrange the stack view. and it worked, but the size of the stack just changed!

 let language = getObjectFromUserDefault(forKey: userDefaultKeys.getLanguageKey) as? String
     if KLanguageCode.Arabic.rawValue == language
     {
        self.mobiStack.removeArrangedSubview(self.mobiStack.arrangedSubviews.first!)
        self.mobiStack.removeArrangedSubview(self.mobiStack.arrangedSubviews.first!)
        self.mobiStack.setNeedsLayout()
        self.mobiStack.layoutIfNeeded()
        self.view.layoutIfNeeded()
        self.mobiStack.insertSubview(self.txtMobile, at: 0)
        self.mobiStack.insertSubview(self.countryCode, at: 1)
        self.mobiStack.setNeedsLayout()
        self.view.layoutIfNeeded()
        
    }

Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
Ali Madhoun
  • 17
  • 1
  • 5
  • Could you provide the code of the UI so we can recreate the problem. At the very least the phone number StackView? – Visal Rajapakse Sep 10 '21 at 15:43
  • 3
    You want to use `self.mobiStack.insertArrangedSubview(...)` instead of `self.mobiStack.insertSubview(...)` – DonMag Sep 10 '21 at 15:48

1 Answers1

0

You can simplify your code like this:

// properly unwrap optional
guard let v = self.mobiStack.arrangedSubviews.last else {
    return
}
self.mobiStack.insertArrangedSubview(v, at: 0)

Notes:

  • when adding arranged subviews, you do NOT need to remove them first.
  • the above code will swap the two views.

You may want to explicitly set the order (instead of just swapping them)... So, you might use a function like this:

func orderFields(_ rtl: Bool) -> Void {
    if rtl {
        self.mobiStack.addArrangedSubview(self.txtMobile)
        self.mobiStack.addArrangedSubview(self.countryCode)
    } else {
        self.mobiStack.addArrangedSubview(self.countryCode)
        self.mobiStack.addArrangedSubview(self.txtMobile)
    }
}

You can call that when you setup your views --

The fields will be ordered as instructed... adding them if they are not already arranged subviews, or re-ordering them if they are.

Also, unless you have something else going on that you have not shown us, there is no need to be calling:

self.mobiStack.setNeedsLayout()
self.view.layoutIfNeeded()
DonMag
  • 69,424
  • 5
  • 50
  • 86