Center align Labels and images inside UIView programatically with Swift

爱⌒轻易说出口 提交于 2019-12-05 07:00:16

问题


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


回答1:


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])


来源:https://stackoverflow.com/questions/29184492/center-align-labels-and-images-inside-uiview-programatically-with-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!