使用Swift以编程方式将UIView内的标签和图像对齐 [英] Center align Labels and images inside UIView programatically with Swift

查看:143
本文介绍了使用Swift以编程方式将UIView内的标签和图像对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在开发应用程序时遇到了一个我似乎无法解决的问题。

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

我正在制作带有标签和图像的uiview。内容需要在视图中居中。

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.

以下是它的外观:

此处文字较长:

正如您所看到的,应该有1个标签左边,中间的一个uiimage和右边的另一个标签都集中在中间,即使文本长度可能不同。

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

}

此时此行已经突破

NSLayoutFormatOptions.AlignAllCenterX

'无法解析约束格式:
选项掩码需要在水平边缘上对齐的视图,对于同样水平的布局,不允许这样做。
H:| - [label] -5- [brainView] - |

'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?

感谢您的帮助

推荐答案

首先,将 .AlignAllCenterX 更改为 .AlignAllCenterY ,原因是H:| - [label] -5- [brainView] - |指定视图如何水平放置,你想要标签 brainView 具有相同的中心Y位置。

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.

其次,制作一个包含所有3个视图的子视图,然后将此子视图置于黑色矩形内。您可以使用 costView 作为子视图。
以下是基于您现有代码的一些修改后的代码。

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

这篇关于使用Swift以编程方式将UIView内的标签和图像对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆