logo
down
shadow

Axis change of stackView giving layout error


Axis change of stackView giving layout error

Content Index :

Axis change of stackView giving layout error
Tag : ios , By : Cadu
Date : November 27 2020, 01:01 AM

will be helpful for those in need First of All viewDidLayoutSubviews is not good option to handle oriantion changes.Apple recommended method is viewWillTransitionToSize. For more details : What is the "right" way to handle orientation changes in iOS 8?
When you first Run your Code ,Stack View Appear With Vertical Distribution , cases both FirstView and Second View have Following Constraint
         Leading =  StackView Leading,
         Trailing =  StackView Trailing,
         Top      = StackView Top,
         height   =   80
            Leading =  StackView Leading    ,
              Top      = FirstView Top,
              Trailing =  StackView Trailing,
              height   =   80
   import UIKit

class ViewController: UIViewController {

    enum DisplayMode {
        case regular
        case compact
    }

    private let stackView = UIStackView(frame: .zero)
    private let firstView = UIView(frame: .zero)
    private let secondView = UIView(frame: .zero)
    private var firstViewWidth: NSLayoutConstraint?
    private var secondViewWidth: NSLayoutConstraint?

    override func viewDidLoad() {
        super.viewDidLoad()

        stackView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(stackView)
        NSLayoutConstraint.activate([
            stackView.topAnchor.constraint(equalTo: view.topAnchor),
            stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            ])

        firstView.backgroundColor = .red
        stackView.addArrangedSubview(firstView)
        firstView.heightAnchor.constraint(equalToConstant: 80).isActive = true
        firstViewWidth = firstView.widthAnchor.constraint(equalTo: stackView.widthAnchor, multiplier: 1/3)
        firstViewWidth?.priority = UILayoutPriority(rawValue: 999)
        firstViewWidth?.isActive = true

        secondView.backgroundColor = .black
        stackView.addArrangedSubview(secondView)
        secondView.heightAnchor.constraint(equalToConstant: 80).isActive = true


        if self.view.bounds.width < 400 {
            self.switchMode(.compact)
        } else {
            self.switchMode(.regular)
        }
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

    }

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)


        coordinator.animate(alongsideTransition: { (context) in

        }) { (context) in
            if self.view.bounds.width < 400 {
                self.switchMode(.compact)
            } else {
                self.switchMode(.regular)
            }
        }

    }

}

private extension ViewController {

    func switchMode(_ mode: DisplayMode) {
        switch mode {
        case .regular:
            stackView.axis = .horizontal
            firstViewWidth?.isActive = true

        case .compact:
            stackView.axis = .vertical
            firstViewWidth?.isActive = false
        }
    }
}

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Stackview axis change is delayed


Tag : ios , By : Nickolas
Date : March 29 2020, 07:55 AM
With these it helps For anyone interested, I managed to solve this by setting the axis in the cell's traitCollectionDidChange method as well. This method is always called when the cell is created and seems to update the layout before the push animation begins.

How to change x-axis layout using plotly in r


Tag : r , By : nd27182
Date : March 29 2020, 07:55 AM
wish of those help Here is something to help you. You can play with shapes and annotations to get exatly what you want.
plot_ly(data2, x = ~Site, y = ~Card, type = 'bar', name = 'Card', marker = list(color = 'Black')) %>%
  add_trace(y = ~Pen, name = 'Pen', marker = list(color = 'red')) %>%
  layout(yaxis = list(title = 'Number of Bee Visits'), 
         barmode = 'stack',  
         font = list(family = 'Times New Roman', size =14, color ="black"), 
         xaxis = list(autotick = F, dtick = 2),
         margin = list(
           r = 10, 
           t = 25, 
           b = 100, 
           l = 110
         ),
         shapes = list(
           list(
             line = list(
               color = "rgba(68, 68, 68, 0.5)", 
               width = 1
             ), 
             type = "line", 
             x0 = 0, 
             x1 = 1, 
             xref = "paper", 
             y0 = -0.05, 
             y1 = -0.05, 
             yref = "paper"
           )
         ),
         annotations = list(
           list(
             x = 0.04, 
             y = -0.1, 
             showarrow = FALSE, 
             text = "15", 
             xref = "paper", 
             yref = "paper"
           ), 
           list(
             x = 0.14, 
             y = -0.1, 
             showarrow = FALSE, 
             text = "16", 
             xref = "paper", 
             yref = "paper"
           ), 
           list(
             x = 0.24, 
             y = -0.1, 
             showarrow = FALSE, 
             text = "17", 
             xref = "paper", 
             yref = "paper"
           ), 
           list(
             x = .35, 
             y = -0.1, 
             showarrow = FALSE, 
             text = "18", 
             xref = "paper", 
             yref = "paper"
           ),
           list(
             x = .45, 
             y = -0.1, 
             showarrow = FALSE, 
             text = "19", 
             xref = "paper", 
             yref = "paper"
           ),
           list(
             x = .55, 
             y = -0.1, 
             showarrow = FALSE, 
             text = "20", 
             xref = "paper", 
             yref = "paper"
           ),
           list(
             x = .65, 
             y = -0.1, 
             showarrow = FALSE, 
             text = "21", 
             xref = "paper", 
             yref = "paper"
           ),
           list(
             x = .75, 
             y = -0.1, 
             showarrow = FALSE, 
             text = "22", 
             xref = "paper", 
             yref = "paper"
           ),
           list(
             x = .85, 
             y = -0.1, 
             showarrow = FALSE, 
             text = "23", 
             xref = "paper", 
             yref = "paper"
           ),
           list(
             x = .95, 
             y = -0.1, 
             showarrow = FALSE, 
             text = "24", 
             xref = "paper", 
             yref = "paper"
           )
         )
         )

When trait collection changes, constraint conflicts arise as though the stackview axis didn't change


Tag : swift , By : Arun Thakkar
Date : March 29 2020, 07:55 AM
will be helpful for those in need Couple notes...
There is an inherent issue with "nested" stack views causing constraint conflicts. This can be avoided by setting the priority on affected elements to 999 (instead of the default 1000). Your layout becomes a bit complex... Labels "attached" to text fields; elements needing to be on two "lines" in portrait orientation or one "line" in landscape; one element of a "multi-element line" having a different height (the stepper); and so on. To get your "field2" and "field3" to be equal size, you need to constrain their widths to be equal, even though they are not subviews of the same subview. This is perfectly valid, as long as they are descendants of the same view hierarchy. Stackviews are great --- except when they're not. I would almost suggest using constraints only. You need to add more constraints, but it might avoid some issues with stack views.
class LabeledFieldStackView: UIStackView {

    var theLabel: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()

    var theField: UITextField = {
        let v = UITextField()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.borderStyle = .roundedRect
        return v
    }()

    convenience init(with labelText: String, fieldText: String, verticalGap: CGFloat) {

        self.init()

        axis = .vertical
        alignment = .fill
        distribution = .fill
        spacing = 2

        addArrangedSubview(theLabel)
        addArrangedSubview(theField)

        theLabel.text = labelText
        theField.text = fieldText

        self.translatesAutoresizingMaskIntoConstraints = false

    }

}

class LargentViewController: UIViewController {

    var rootStack: UIStackView!

    var fieldStackView1: LabeledFieldStackView!
    var fieldStackView2: LabeledFieldStackView!
    var fieldStackView3: LabeledFieldStackView!
    var fieldStackView4: LabeledFieldStackView!

    var stepper: UIStepper!

    var fieldAndStepperStack: UIStackView!

    var twoLineStack: UIStackView!

    var fieldAndStepperStackWidthConstraint: NSLayoutConstraint!

    // horizontal gap between elements on the same "line"
    var horizontalSpacing: CGFloat!

    // vertical gap between "lines"
    var verticalSpacing: CGFloat!

    // vertical gap between labels above text fields
    var labelToFieldSpacing: CGFloat!

    override func viewDidLoad() {

        super.viewDidLoad()

        view.backgroundColor = UIColor(white: 0.9, alpha: 1.0)

        horizontalSpacing = CGFloat(2)
        verticalSpacing = CGFloat(8)
        labelToFieldSpacing = CGFloat(2)

        createIntializeViews()
        createInitializeStacks()
        fillStacks()

    }

    private func createIntializeViews() {

        fieldStackView1 = LabeledFieldStackView(with: "label 1", fieldText: "field 1", verticalGap: labelToFieldSpacing)
        fieldStackView2 = LabeledFieldStackView(with: "label 2", fieldText: "field 2", verticalGap: labelToFieldSpacing)
        fieldStackView3 = LabeledFieldStackView(with: "label 3", fieldText: "field 3", verticalGap: labelToFieldSpacing)
        fieldStackView4 = LabeledFieldStackView(with: "label 4", fieldText: "field 4", verticalGap: labelToFieldSpacing)

        stepper = UIStepper()

    }

    private func createInitializeStacks() {

        rootStack = UIStackView()
        fieldAndStepperStack = UIStackView()
        twoLineStack = UIStackView()

        [rootStack, fieldAndStepperStack, twoLineStack].forEach {
            $0?.translatesAutoresizingMaskIntoConstraints = false
        }

        // rootStack has spacing of horizontalSpacing (inter-line vertical spacing)
        rootStack.axis = .vertical
        rootStack.alignment = .fill
        rootStack.distribution = .fill
        rootStack.spacing = verticalSpacing

        // fieldAndStepperStack has spacing of horizontalSpacing (space between field and stepper)
        // and .alignment of .bottom (so stepper aligns vertically with field)
        fieldAndStepperStack.axis = .horizontal
        fieldAndStepperStack.alignment = .bottom
        fieldAndStepperStack.distribution = .fill
        fieldAndStepperStack.spacing = horizontalSpacing

        // twoLineStack has inter-line vertical spacing of
        //   verticalSpacing in portrait orientation
        // for landscape orientation, the two "lines" will be changed to one "line"
        //  and the spacing will be changed to horizontalSpacing
        twoLineStack.axis = .vertical
        twoLineStack.alignment = .leading
        twoLineStack.distribution = .fill
        twoLineStack.spacing = verticalSpacing

    }

    private func fillStacks() {

        self.view.addSubview(rootStack)

        // constrain rootStack Top, Leading, Trailing = 20
        // no height or bottom constraint
        NSLayoutConstraint.activate([
            rootStack.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20.0),
            rootStack.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 20.0),
            rootStack.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -20.0),
            ])

        rootStack.addArrangedSubview(fieldStackView1)

        fieldAndStepperStack.addArrangedSubview(fieldStackView2)
        fieldAndStepperStack.addArrangedSubview(stepper)

        twoLineStack.addArrangedSubview(fieldAndStepperStack)
        twoLineStack.addArrangedSubview(fieldStackView3)

        rootStack.addArrangedSubview(twoLineStack)

        // fieldAndStepperStack needs width constrained to its superview (the twoLineStack) when
        //  in portrait orientation
        // setting the priority to 999 prevents "nested stackView" constraint breaks
        fieldAndStepperStackWidthConstraint = fieldAndStepperStack.widthAnchor.constraint(equalTo: twoLineStack.widthAnchor, multiplier: 1.0)
        fieldAndStepperStackWidthConstraint.priority = UILayoutPriority(rawValue: 999)

        // constrain fieldView3 width to fieldView2 width to keep them the same size
        NSLayoutConstraint.activate([
            fieldStackView3.widthAnchor.constraint(equalTo: fieldStackView2.widthAnchor, multiplier: 1.0)
            ])

        rootStack.addArrangedSubview(fieldStackView4)

    }

    override public func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {

        super.traitCollectionDidChange(previousTraitCollection)

        if traitCollection.verticalSizeClass == .regular {
            fieldAndStepperStackWidthConstraint.isActive = true
            twoLineStack.axis = .vertical
            twoLineStack.spacing = verticalSpacing
        } else if traitCollection.verticalSizeClass == .compact {
            fieldAndStepperStackWidthConstraint.isActive = false
            twoLineStack.axis = .horizontal
            twoLineStack.spacing = horizontalSpacing
        } else {
            print("Unexpected")
        }
    }

}

iOS: Change height of TextField in StackView (inside StackView)


Tag : ios , By : Atanas
Date : March 29 2020, 07:55 AM
wish help you to fix your issue Here is one solution - assuming you want each "row" in your stack view to be 52-pts tall (labels have green background, just to make their frames easier to see).
Alignment: Fill
Distribution: Fill Equally
Spacing: 10
Alignment: Center
Distribution: Fill Equally
Spacing: 0

Can we change the x-axis in an ascending order while giving a constraint


Tag : python , By : rusl
Date : March 29 2020, 07:55 AM
This might help you IIUC, you need to just plot the elements of the list (except the last one) in descending order. This can be done by sorting all but the last element of the list and then appending the last element to the reverse sorted list. The reverse sorting (descending order) can be done by first sorting the list and then reversing it using [::-1]. If this is not what you want, drop a comment below
import matplotlib.pyplot as plt 

left = [1, 2, 3, 4, 5] 
height = [10, 24, 36, 40, 5] 
tick_label = ['one', 'two', 'three', 'four', 'five'] 

height_plot = sorted(height[:-1])[::-1] + height[-1:]

plt.bar(left, height_plot, tick_label = tick_label, 
        width = 0.8, color = ['red', 'green']) 

plt.xlabel('x - axis') 
plt.ylabel('y - axis') 
plt.title('My bar chart!') 
plt.show()
height_plot = sorted(height[:-1])[::-1] + height[-1:]
new_labels = tick_label[:-1][::-1] + tick_label[-1:]

plt.bar(left, height_plot, tick_label = new_labels, 
        width = 0.8, color = ['red', 'green']) 
Related Posts Related QUESTIONS :
  • iOS Unity Firebase Messenger Xcode Compile Error: FIRDynamicLinks
  • Firebase Storage Image Cache not updating SWIFT
  • unhandled js exception: application main has not been registered expo TestFlight
  • App freezes on IOS when navigate to another screen - React Navigation
  • How to create haptic feedback for a Button in SwiftUI?
  • How can I achieve automatic scrolling in my text view when text comes down to the keyboard level in Swift?
  • how to get the location with the CLLocationManager every 10 secondes?
  • Calling completion handler of a function from Timer selector function Swift
  • How to make SwiftUI view fullscreen?
  • RAM, JSC, Views, UI and JS usage table appearing whenever I launch my react native app. How to remove this table?
  • Change status bar background color using UIStatusBarManager
  • Should we make tapGesture component an IBAction or IBOutlet to capture the tap event?
  • Iframe automatically goes full screen using Ionic 3.9.2 on iOS
  • How to calculate score out of 1000 given some seconds (In Double)
  • How to calculate time (minutes) between two dates in swift?
  • There was problem loading requested app.it looks like you may be using LAN URL
  • Swift circular corners doesn't work properly on different screen sizes
  • How change .navigationBarTitle font in SwiftUI?
  • What happens if `MPSCNNConvolutionDataSource` protocol's `load` method return false?
  • Why does the UIBarButtonItem not show up when I create it with code?
  • How to prevent following view controller inheriting navigation view controller bar?
  • What does it mean when .xcodeproj files are shown in red in Xcode?
  • Xcode SwiftUI how to scroll the Preview Canvas?
  • Expand tableview and increase scrollview content size by an appropriate difference on clicking a button inside a table c
  • xcodebuild failed with return code: 65 - using CLI/Appcenter but no error messages
  • "'isDeveloperModeEnabled' is deprecated: This no longer needs to be set during development. " What is isDevelo
  • Right click in UIKit for Mac
  • How we Support Dark Mode in Current iOS App with iOS 13?
  • Security vulnerablility issue in ios mobile app
  • How to set a background color for the viewController in swiftUI?
  • SwiftUI : Segue navigation
  • iOS 13 Custom UISearchBar _searchField crash
  • USDZ models have holes in SceneKit but not QuickLook
  • Why does iOS Password Autofill not prompt to save password on keychain?
  • Pushing information to firebase after event is created(Firebase-Realtime-Database)
  • Xcode 11 Beta and Carthage bootstrap
  • How to change the status bar background color and text color on iOS 13?
  • Using Core Data with SwiftUI
  • How should I do to wait all the data downloaded completely and show on TableView?
  • Can we specify the number of rows that can be shown in each section of a collection view
  • Why sometimes completion handler not called?
  • Protocol 'View' can only be used as a generic constraint because it has Self or associated type requirements
  • In UIKit we can set label.numberOfLines = 0 when we do not know how many lines the text will take? What is the alternati
  • Swift ISO8601 format to Date returning fatal error
  • SwiftUI Login Page Layout
  • Xcode: Could not locate installed application. Install claimed to have succeeded, but application could not be found on
  • See the TestFlight crash log in the Xcode
  • Why does zero UIView's CALayer.speed stops UIAlertController's buttons from working?
  • Firestore collectionGroup query returns empty result
  • Modify text in SwiftUI
  • CNCopyCurrentNetworkInfo with iOS 13
  • WWDC 2019 - iOS13 April 2020 requirement
  • Nativescript IPhone X - How to "hide" home indicator behind two swipes to go to home screen
  • Should I use a singleton location manager in Swift?
  • Accessibility problem in reusable TableViewCell
  • Remove top line containing Done button from Keyboard Using Storyboard or in Swift
  • Swift Storyboard - Centring an Icon and multi-line text horizontally
  • viewDidAppear is delayed by 0.5 sec
  • Pass URL values to SecondView Controller WebView (WKWebView)
  • How to upload images faster on iOS, when using takePictureAsync?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com