对xib swift内部标签的自动约束

时间:2015-08-07 00:10:17

标签: ios swift constraints xib nib

我创建了一个nib文件,用于将自定义视图加载到ViewController中。自定义视图具有:  .background图像填充整个视图(我用它作为背景)  .label里面我需要根据背景图片的大小放在特定的位置。

我设法使用Storyboard中的AutoLayout根据屏幕大小调整背景图像的大小。它可以通过“Aspect Fit”缩小。 但我想以与调整背景图像相同的比例更改标签的约束。意思是,如果背景图像缩小了一半,我希望标签的约束改变一半。这样,它们将始终显示在与图像相同的位置。

但是我在标签的故事板中创建的约束保持不变,我无法弄清楚如何以编程方式操纵标签的约束。

这是定义自定义XIB视图的自定义类的代码:     导入UIKit

@IBDesignable class TestView:UIView {

var view: UIView!
var nibName = "TestView"

@IBOutlet weak var backImage: UIImageView!
@IBOutlet weak var upcomingLabel: UILabel!

@IBInspectable var Background: UIImage? {
    get {
        return backImage.image
    }
    set(Background) {
        backImage.image = Background
    }
}
@IBInspectable var maintenance: String? {
    get {
        return upcomingLabel.text
    }
    set(maintenance) {
        upcomingLabel.text = maintenance
    }
}

//MARK -    Implement both CustomView initializers: init(coder:) and init(frame:)
override init(frame: CGRect) {
    super.init(frame: frame)
    xibSetup()
}
required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    xibSetup()
}

func xibSetup() {
    view = loadViewFromNib()
    view.frame = bounds

    addSubview(view)
}
func loadViewFromNib() -> UIView {
    let bundle = NSBundle(forClass: self.dynamicType)
    let nib = UINib(nibName: nibName, bundle: bundle)
    let view = nib.instantiateWithOwner(self, options: nil) [0] as! UIView

    return view
}
}

以下是我在View控制器中添加视图的方法:

import UIKit

class TestVC: UIViewController {

@IBOutlet weak var customViewContainer: UIView!

override func viewDidLoad() {
    super.viewDidLoad()

    let customView = TestView()
    customView.setTranslatesAutoresizingMaskIntoConstraints(false)
    customViewContainer.addSubview(customView)

    //Add constraint to the view
    let viewDictionary = ["custom": customView, "view": view]

    let constraintH = NSLayoutConstraint.constraintsWithVisualFormat("H:|[custom]", options: NSLayoutFormatOptions(0), metrics: nil, views: viewDictionary)
    let constraintV = NSLayoutConstraint.constraintsWithVisualFormat("V:|[custom]", options: NSLayoutFormatOptions(0), metrics: nil, views: viewDictionary)
    let constraintWidth = NSLayoutConstraint(item: customView, attribute: .Width, relatedBy: .Equal, toItem: customViewContainer, attribute: .Width, multiplier: 1, constant: 0)
    let constraintHeight = NSLayoutConstraint(item: customView, attribute: .Height, relatedBy: .Equal, toItem: customViewContainer, attribute: .Height, multiplier: 1, constant: 0)

    view.addConstraints(constraintH as [AnyObject])
    view.addConstraints(constraintV as [AnyObject])
    view.addConstraint(constraintWidth)
    view.addConstraint(constraintHeight)

}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}
}

我对此失去了理智,帮助!

0 个答案:

没有答案