2017-02-23 67 views
0

我的ViewController和里面UICollectionView,我试图UILable添加到UICollectionView编程:无法修改UICollectionView内的UILabel框架?

let Label: UILabel = { 
    let label = UILabel() 
    label.text = "Sample Text Here" 
    label.textAlignment = .center 
    label.textColor = UIColor(white: 0.4, alpha: 0.4) 
    label.font = UIFont.systemFont(ofSize: 20) 
    return label 
}() 

override func viewDidLoad() { 
    super.viewDidLoad() 

    Label.translatesAutoresizingMaskIntoConstraints = false 
    Label.frame = CGRect(x: 0, y: 40, width: view.frame.width, height: 20) 
    collectionView.addSubview(Label) 
} 

where the label's position is not the same as x:0 , y: 40

,当我试图改变y值是相同

当我试图像这样添加它:view.addSubView(Label)根本没有出现。

注:如果没有数据来填充细胞

+2

不要将子视图添加到collectionView。创建UICollectionViewCell并将标签添加到单元格 – Bhanupriya

+0

@Bhanupriya如果没有单元格填充,标签将出现 –

回答

1

它的工作原理标签应该出现..

override func viewDidLoad() { 
    super.viewDidLoad() 

    let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 300, height: 300), collectionViewLayout: UICollectionViewFlowLayout()) 

    self.view.addSubview(collectionView) 
    collectionView.backgroundColor = UIColor.red 

    let label = UILabel() 
    label.text = "Sample Text Here" 
    label.textAlignment = .center 
    label.textColor = UIColor(white: 0.4, alpha: 0.4) 
    label.font = UIFont.systemFont(ofSize: 20) 

    label.frame = CGRect(x: 0, y: 100, width: view.frame.width, height: 20) 
    collectionView.addSubview(label) 

} 

小心直接将标签贴到的CollectionView,虽然。 你可以创建一个uiview,并为其添加标签和集合(当然有适当的集合视图布局)。使用收集视图只用于显示单元格,并添加任何东西到cell.contentView如果你愿意

谢谢。