收集单元格内容大小

时间:2018-04-30 11:33:01

标签: ios swift uicollectionview uikit uicollectionviewcell

我在CollectionViewCell中添加了一个视图作为父红色视图,在父视图的中心添加了下一个蓝色子视图。它正常工作,子视图位于父视图的中心,不会更改集合单元格大小。但是,通过符合UICollectionViewDelegateFlowLayout协议中的方法来更改单元格大小,并且视图不是正确的单元格的中心。我怎么能解决这个问题?

class ItemCollectionViewCell: UICollectionViewCell {  
   var parentView: UIView!
   var circularView: UIView!    
   var itemImage: UIImageView!    
   var itemName: UILabel!   
   override init(frame: CGRect) {
    super.init(frame: frame)       
     //  self.updateView()
   }

   required init?(coder aDecoder: NSCoder) {
      super.init(coder: aDecoder)
      self.updateView()
   }

   func updateView(){
      self.clipsToBounds = true
      self.parentView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 
         self.frame.size.width, height: self.frame.size.height))

      self.parentView.backgroundColor = UIColor.red
      self.circularView = UIView(frame: CGRect(x: 0, y: 0, width: 
        self.parentView.frame.size.width / 4 , height: 
          self.parentView.frame.size.width / 4 ))
      self.circularView.backgroundColor = UIColor.blue
      self.addSubview(parentView)
      self.parentView.addSubview(self.circularView)
      self.circularView.center = self.parentView.center
  }
}

Before conform protocol and size is not changed for indexPath[![View is not centered correctly 1] 2

3 个答案:

答案 0 :(得分:0)

试试此代码

self.circularView.center = CGPoint(x: self. parentView.bounds.midX, y: self. parentView.bounds.midY)
self.parentView.addSubview(self.circularView)
self.addSubview(parentView)

答案 1 :(得分:0)

尝试做:

self.circularView.center = CGPointMake(CGRectGetMidX(self.parentView.bounds), CGRectGetMidY(self.parentView.bounds))

为什么这应该有效?尝试检查每个单元格的self.parentView.center值,它们可能不是您想要的值,因为center property给出了与父视图坐标系相关的值。

答案 2 :(得分:0)

从updateView()

中删除以下行
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    this.spinnerService.start();
    return next.handle(req).finally(res => this.spinnerService.stop() );
  }

请将其添加到以下方法中:

self.circularView.center = self.parentView.center

e.g。

override func layoutSubviews() {
        super.layoutSubviews()
        self.circularView.center = self.parentView.center
}