Search code examples
iosswiftautolayout

how to set autolayout for label between 2 stack view?


I am a beginner, and I really need your help. autolayout for UILabel really really confused me :(

I want the end result to be like this in portrait in all iPhone Device.

enter image description here

I have made "attend" and "09:00" to be one stack view, and make it vertically in container and 8 point leading space to container like this enter image description here

I also have made "running" and "7h 32m" to be another one stackview, and make it vertically in container and 8 point trailing space to container like this enter image description here

so I think that 2 stack view will always be in that position.

I also have 2 UIView as a vertical line, and it has 8 point gap to each stackview.

the problem is in the middle part, especially "example note example note example note ". I want that note UILabel to be 8 point gap to the each vertical line. but when I add 8 point gap to the each vertical line, the those 2 stack view shifted and I dont understand why. could you please help me why this is happened?

enter image description here

enter image description here

enter image description here


Solution

  • Drag three UIView to StoryBoard. Name it as, ATTENDVIEW, NOTEVIEW and RUNNINGVIEW

    Select all the three and Embed in StackView.

    StackView axis is Horizontal, alignment and distribution as FILL, spacing 2.

    Set StackView Constraints as, top 15, left and right is 0, height as 70.

    Set Width Constraints as 70 for, ATTENDVIEW and RUNNINGVIEW. Dont give any constraints to NOTEVIEW.

    For both ATTENDVIEW and RUNNINGVIEW, add single UILabel each. Name it as, AttendTextLabel and RunningTextLabel .

    For, both, AttendTextLabel and RunningTextLabel, set numberOfLines as 2 and Constraints as top, bottom, left and right as 4.

    Coding

        //ATTRIBUTE TEXT FOR UILABEL - USE THIS FOR TWO LABEL
        let main_string = "Attend\n09:00"
        let string_to_color = "09:00"
    
        let range = (main_string as NSString).range(of: string_to_color)
    
        let attribute = NSMutableAttributedString.init(string: main_string)
    
        attribute.addAttributes([NSForegroundColorAttributeName : UIColor.white], range: range)
    
        AttendTextLabel.textColor = UIColor.black
    
        AttendTextLabel.attributedText = attribute
    

    Storyboard

    enter image description here

    Output

    enter image description here