Swift:将一个xib添加到UIView中 [英] Swift: Add a xib into a UIView

查看:548
本文介绍了Swift:将一个xib添加到UIView中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想添加自定义UIView。我的自定义视图的类定义是:

I would like to add a custom UIView. The class definition of my custom view is:

class UserCoinView: UIView {
    @IBOutlet weak var userName: UILabel!
    @IBOutlet weak var coinView: UIView!
    @IBOutlet weak var coinAmount: UILabel!
    @IBOutlet weak var coinIcon: UILabel!

    override func drawRect(rect: CGRect) {
        let smartCoins = SmartShopperUtil.getSmartShopper().smartCoins

        if smartCoins != nil && smartCoins >= 0  {
            coinAmount.text = String(smartCoins!)
            coinView.backgroundColor = SmartShopperUtil.getSmartCoinBackgroundColor(SmartShopperUtil.getSmartShopper().smartCoins!)
        }

        userName.text = SmartShopperUtil.getSmartShopperNameWithFullName(SmartShopperUtil.getSmartShopper().name)
        coinIcon.text = AEVIcons.AEV_SMART_COIN
    }
}

我在ViewController中添加了一个View我要添加此视图,我已将此视图的自定义类设置为UserCoinView。之后,我已经连接到ViewController,在这个ViewController中,我不知道该怎么做才能显示我的自定义UIView。

I have added a View in the ViewController I want to add this view, and I have set the custom class of this view as UserCoinView. After that, I have made a connection to the ViewController, and in this ViewController I have no idea what to do in order to display my custom UIView.

提前感谢你的帮助。

推荐答案

有几种方法可以做到这一点。

There is couple of ways you can do this.

以编程方式添加为子视图。

如果您使用自动布局,那么更好的地方是 viewDidLayoutSubviews 方法。

If you use autolayout, better place for that is viewDidLayoutSubviews method.

var myCustomView: UserCoinView? // declare variable inside your controller
override func viewDidLayoutSubviews() {
  super.viewDidLayoutSubviews()
  if myCustomView == nil { // make it only once
    myCustomView = NSBundle.mainBundle().loadNibNamed("UserCoinView", owner: self, options: nil).first as? UserCoinView
    myCustomView.frame = ...
    self.view.addSubview(myCustomView) // you can omit 'self' here
    // if your app support both Portrait and Landscape orientations 
    // you should add constraints here
  }
}

在InterfaceBuilder中添加为子视图。

您只需要在故事板中为您的控制器添加一个空视图,并在Identity Inspector中为此视图指定您的类。之后,如果需要,可以将插座拖放到控制器类中。

You simply need put an empty view to you controller inside the storyboard, and assign your class for this view in Identity Inspector. After that, you can drag-n-drop outlets to your controller classes if you need one.

至于我,我更喜欢第二种方法,因为你不需要以编程方式硬编码帧/创建约束,只需添加autolayout。

As for me, I prefer the second method because you don't need to hardcode frame / create constraints programmatically, just add autolayout.

这篇关于Swift:将一个xib添加到UIView中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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