如何在不使用nil值的情况下使用现有的故事板在运行时中创建新视图

时间:2019-04-17 14:28:30

标签: ios swift xcode

我需要设置一个视图以将其转换为UIImage,但是我获取的是视图内部组件的零值。

这是我的viewClass

class MarkerView: UIViewController{

    @IBOutlet var marker: UIView!
    @IBOutlet weak var lblAddress: UILabel!
    @IBOutlet weak var colorView: UIView!
    @IBOutlet weak var imageView: UIImageView!

    func setupView(Image: UIImage, Title: String, Color: UIColor){
        _ = self.view
        self.colorView.backgroundColor = Color
        self.imageView.image = Image
        self.lblAddress.text = Title
    }
}

这是我的来电者

let marker = MarkerView.init()
marker.setupView(Image:#imageLiteral(resourceName: "personMarker.png") , Title: trip.from.address, Color: UIColor(red: 0.09, green: 0.5, blue: 0.76, alpha: 1))

我所有的IBOutlets都获得nil值,但它们都连接到StoryBoard

1 个答案:

答案 0 :(得分:-1)

当@IBoutlet对象不存在时,您不能对其进行初始化,因为一个对象需要定义一个框架或对其施加4个约束。但是,您可以创建UIView并通过3种方式将其添加到另一个视图中:

let newview = UIView(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
//You can choose one of them
view.addSubview(newview)
view.insertSubview(newview, at: 0)// at Items number
view.insertSubview(newview, aboveSubview: anotherView)//put new view above the anotherView
view.insertSubview(newview, belowSubview: anotherView)//put new view below the anotherView

此外,如果您想对该视图施加约束,则可以使用以下代码来实现:

let newview = UIView(frame: .zero)
view.addSubview(newview)
newview.translatesAutoresizingMaskIntoConstraints = false
let centreX = NSLayoutConstraint(item: newview, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0)
let centreY = NSLayoutConstraint(item: newview, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1, constant: 0)
let width = NSLayoutConstraint(item: newview, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100)
let height = NSLayoutConstraint(item: newview, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100)
view.addConstraints([centreX, centreY])
newview.addConstraints([width, height])