awakeFromNib、initWithCoder求解!



新手,最近看视频发现这俩有点混

直接上问题:
今天看视频
通过xib创建,
接着NSBundle mainBundle] loadNibNamed加载
然后尝试在initWithCoder里创建子控件,计算frame时会用到xib中view的frame
但是,取到的xib上面的view的frame 等于空

最后在awakeFromNib里就能取到 xib中view的frame


看视频,这两方法经常会用,但是没搞清,两者到底什么情况下调用 ,感觉功能差不多。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个使用UICollectionView来实现九宫格图片显示的简单示例代码: 1. 在Storyboard中拖拽一个UICollectionView控件,并设置其约束和相关属性。 2. 创建一个UICollectionViewCell的子类,命名为ImageCell,并在Storyboard中设置其样式和布局。 3. 在ViewController中添加以下代码: ```swift import UIKit class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { @IBOutlet weak var collectionView: UICollectionView! let images: [UIImage] = [UIImage(named: "image1")!, UIImage(named: "image2")!, UIImage(named: "image3")!, UIImage(named: "image4")!, UIImage(named: "image5")!, UIImage(named: "image6")!] override func viewDidLoad() { super.viewDidLoad() collectionView.dataSource = self collectionView.delegate = self } // MARK: - UICollectionViewDataSource func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return images.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as! ImageCell cell.imageView.image = images[indexPath.row] return cell } // MARK: - UICollectionViewDelegate func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { // TODO: 处理选中事件 } } ``` 4. 最后,在ImageCell中添加以下代码: ```swift import UIKit class ImageCell: UICollectionViewCell { @IBOutlet weak var imageView: UIImageView! override func awakeFromNib() { super.awakeFromNib() imageView.layer.cornerRadius = 8.0 imageView.layer.masksToBounds = true } } ``` 这样就可以在UICollectionView中显示九宫格图片了。当然,你可以根据自己的需求对代码进行修改和优化。希望对你有帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值