简体   繁体   中英

Center align Labels and images inside UIView programatically with Swift

Im working on an app and came across a problem that I cant seem to solve.

I am making a uiview with labels and images inside it. The content needs to be centered inside the view.

The problem is that the label will hold different lenght texts and the view itself will have different width depending on where it is used.

Here is how it should look:

在此处输入图片说明

And here with longer text:

在此处输入图片说明

As you can see there should be 1 label to the left, one uiimage in the middle and another label to the right all centered to the middle even though the text length could be different.

This is what I have so far in code. I need to do this programatically if possible. Im running a method to create the button depending on a value.

    func cost(cost:Int){

    costView = UIView()
    costView?.setTranslatesAutoresizingMaskIntoConstraints(false)
    self.costView?.clipsToBounds = true
    self.addSubview(costView!)


    self.costLabel.frame = CGRectMake(0, 0, 60, self.bounds.size.height)
    self.costLabel.textAlignment = NSTextAlignment.Right
    self.costLabel.textColor = UIColor.whiteColor()
    self.costLabel.font = Services.exoFontWithSize(16)
    self.costLabel.text = String(cost)
    costView?.addSubview(costLabel)



    self.costBrainImageView = UIImageView(frame: CGRectMake(0, 0, self.bounds.size.height, self.bounds.size.height))
    self.costBrainImageView?.image = Graphics.maskImageNamed("CommonMediumBrain", color: UIColor.whiteColor())
    self.costBrainImageView?.contentMode = UIViewContentMode.ScaleAspectFill
    costView?.addSubview(costBrainImageView!)




    self.label.adjustsFontSizeToFitWidth = true
    self.label.setTranslatesAutoresizingMaskIntoConstraints(false)
    self.label.numberOfLines = 1
    self.label.minimumScaleFactor = 0.20
    self.label.textAlignment = NSTextAlignment.Right
    self.label.font = Services.exoFontWithSize(20)


    //Constraints
    var viewsDict = Dictionary <String, UIView>()
    viewsDict["label"] = label
    viewsDict["brainView"] = costView


    self.addConstraints(
        NSLayoutConstraint.constraintsWithVisualFormat(
            "V:|[label]|", options: nil, metrics: nil, views: viewsDict))
    self.addConstraints(
        NSLayoutConstraint.constraintsWithVisualFormat(
            "V:|[brainView]|", options: nil, metrics: nil, views: viewsDict))
    self.addConstraints(
        NSLayoutConstraint.constraintsWithVisualFormat(
            "H:|-[label]-5-[brainView]-|", options: NSLayoutFormatOptions.AlignAllCenterX, metrics: nil, views: viewsDict))

}

For the moment this breaks since this line

NSLayoutFormatOptions.AlignAllCenterX

'Unable to parse constraint format: Options mask required views to be aligned on a horizontal edge, which is not allowed for layout that is also horizontal. H:|-[label]-5-[brainView]-|

If i remove that everything is aligned to the left and not centered but im not sure this is the right way to accomplish what i want to do.

Any clues on how to solve this?

Thanks for any help

Firstly, change .AlignAllCenterX to .AlignAllCenterY , the reason is that "H:|-[label]-5-[brainView]-|" specifies how views position horizontally, you want label and brainView to have the same center Y position.

Secondly, make a subview that contains all 3 views, then center this subview inside the black rectangle. You can use costView as the subview. Below is some modified code based on your existing code.

costView!.addSubview(label)

//Constraints
var viewsDict = Dictionary <String, UIView>()
viewsDict["label"] = label
viewsDict["brainView"] = costBrainImageView
viewsDict["costLabel"] = costLabel

costView!.addConstraints(
    NSLayoutConstraint.constraintsWithVisualFormat(
        "V:|[label]|", options: nil, metrics: nil, views: viewsDict))
costView!.addConstraints(
    NSLayoutConstraint.constraintsWithVisualFormat(
        "V:|[brainView]|", options: nil, metrics: nil, views: viewsDict))
costView!.addConstraints(
    NSLayoutConstraint.constraintsWithVisualFormat(
        "V:|[costLabel]|", options: nil, metrics: nil, views: viewsDict))
costView!.addConstraints(
    NSLayoutConstraint.constraintsWithVisualFormat(
        "H:|-[label]-5-[brainView]-5-[costLabel]-|", options: NSLayoutFormatOptions.AlignAllCenterY, metrics: nil, views: viewsDict))
costView!.backgroundColor = UIColor.redColor()

// center costView inside self
let centerXCons = NSLayoutConstraint(item: costView!, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: 0);
let centerYCons = NSLayoutConstraint(item: costView!, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0);
self.addConstraints([centerXCons, centerYCons])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM