Swift 3:无法以编程方式正确地在 Collectionview 标头上创建标签? [英] Swift 3: Cant programmatically create label on Collectionview header properly?
问题描述
好的,所以我在这里使用 Swift 3 并且我是 uicollectionviews 的新手.我正在尝试以编程方式将标签添加为我的集合视图中标题 UICollectionReusableView
的子视图.我已经像任何其他视图一样添加了标签,但我一生都无法将标签居中放置在标题上.
Alright, so Im working in Swift 3 here and Im new to uicollectionviews. I am trying to programmatically add a label as a subview of a header UICollectionReusableView
in my collection view. I have added the label like any other view, but I cant for the life of me CENTER the label on the header.
这里是我在自定义header类中的标签代码,在storyboard中添加到header中:
Here is my label code in the custom header class, which is added to the header in the storyboard:
let pointsLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
self.customInit()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.customInit()
}
func customInit() {
//center inside content
pointsLabel.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: 100)
pointsLabel.center = CGPoint(x: self.bounds.width * 0.5, y: self.bounds.height * 0.5)
pointsLabel.textColor = UIColor.darkGray
pointsLabel.textAlignment = .center
pointsLabel.text = "Testing 123"
pointsLabel.font = UIFont(name: "Montserrat", size: 30)
self.addSubview(pointsLabel)
}
我的 Collectionview 确实有两边的边距:
My Collectionview does have a margin on either side:
self.collectionView.contentInset = UIEdgeInsets(top: 0, left: 32.5, bottom: 0, right: 32.5)
然而,这只会影响标题视图的大小,这意味着标签仍应以 header.bounds.width * 0.5 为中心.我将文本对齐居中,但文本向左倾斜:
However that should just affect the size of the header view, meaning the label should still be centered at the header.bounds.width * 0.5. And I centered the text alignment, yet the text is skewed to the left:
如果有帮助,我的收藏视图位于消息应用扩展程序中,但我不知道这会如何改变事情.这里有什么问题?
If it helps, my collection view is within an message app extension, but again I don't know how that would change things. What is wrong here?
即使有:
pointsLabel.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: 100)
//pointsLabel.center = CGPoint(x: self.bounds.width * 0.8, y: self.bounds.height * 0.5)
pointsLabel.center = self.center
pointsLabel.textColor = UIColor.darkGray
pointsLabel.backgroundColor = UIColor.blue
或者将我的宽度更改为更小,我得到:
Or changing my width to less, I get:
为什么?
推荐答案
如果你有页眉和页脚所以你可以用下面的代码替换 viewForSupplementaryElementOfKind 函数
If you have both header and footer so You may replace viewForSupplementaryElementOfKind function with below code
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionElementKindSectionHeader:
let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier:
headerId, for: indexPath) as! CustomHeader
return header
default:
return UIHeaderView()
}
}
这篇关于Swift 3:无法以编程方式正确地在 Collectionview 标头上创建标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!