无法查看更改其大小的视图

时间:2018-11-10 15:52:19

标签: ios swift uicollectionview

我在origin内有一个UIImageView(对于ForecastCell Class),无论如何,我无法在单元格内使用UICollectionView来更改其大小。这是我尝试过的:

UIImageView

这是mWeatherIcon:

private func setupWeatherIcon(){
    self.addSubview(mWeatherIcon)

   //mWeatherIcon.frame.size.width = CGFloat(self.frame.width) / 2
   //mWeatherIcon.frame.size.height = CGFloat(self.frame.height) / 2
   mWeatherIcon.frame.size.width = 20
   mWeatherIcon.frame.size.height = 20

   mWeatherIcon.centerXAnchor.constraint(equalTo: self.safeAreaLayoutGuide.centerXAnchor).isActive = true
   mWeatherIcon.centerYAnchor.constraint(equalTo: self.safeAreaLayoutGuide.centerYAnchor).isActive = true
}

无论我设置了什么宽度和高度,它始终保持相同的宽度和高度。

1 个答案:

答案 0 :(得分:1)

您需要宽度和高度限制

self.contentView.addSubview(mWeatherIcon)

NSLayoutConstraint.activate([
   mWeatherIcon.centerXAnchor.constraint(equalTo:contentView.centerXAnchor),
   mWeatherIcon.centerYAnchor.constraint(equalTo:contentView.centerYAnchor),
   mWeatherIcon.widthAnchor.constraint(equalTo:contentView.widthAnchor,multiplier:0.5),
   mWeatherIcon.heightAnchor.constraint(equalTo:contentView.heightAnchor,multiplier:0.5)
])

别忘了实现此方法

func collectionView(_ collectionView: UICollectionView, 
                  layout collectionViewLayout: UICollectionViewLayout, 
           sizeForItemAt indexPath: IndexPath) -> CGSize