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