我有一个看起来像这样的自定义单元类:
class CollectionViewCell: UICollectionViewCell {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
var textLabel: UILabel = UILabel()
var buttonView: UIButton!
var id: String = String()
override init(frame: CGRect) {
super.init(frame: frame)
let textFrame = CGRect(x: buttonView.center.x - self.frame.width/2, y: 90, width: frame.size.width, height: frame.size.height/3)
textLabel = UILabel(frame: textFrame)
textLabel.font = UIFont.systemFontOfSize(UIFont.smallSystemFontSize())
textLabel.textAlignment = .Center
contentView.addSubview(textLabel)
buttonView = UIButton.buttonWithType(UIButtonType.System) as! UIButton
buttonView.frame = CGRect(x: frame.width / 2 - frame.width * 0.4, y: 0 + textLabel.frame.size.height, width: frame.size.width * 0.8, height: frame.size.height * 0.8 )
contentView.addSubview(buttonView)
}
}
我使单元格出队的函数看起来像这样:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
switch collectionView{
case collectionViewOne!:
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewDetailCell", forIndexPath: indexPath) as! CollectionViewDetailCell
cell.backgroundColor = UIColor.whiteColor()
cellHeightOne = cell.frame.height
cell.productLabel.text = "\(array[indexPath.row].name)"
cell.textLabel.numberOfLines = 0
let myText = NSString(format: self.array[indexPath.row].description)
let paragraphStyle = NSMutableParagraphStyle() as NSMutableParagraphStyle
paragraphStyle.alignment = NSTextAlignment.Justified
let attributes: NSDictionary = [NSFontAttributeName: UIFont.systemFontOfSize(12), NSBaselineOffsetAttributeName: 0, NSParagraphStyleAttributeName: paragraphStyle, NSForegroundColorAttributeName: UIColor.grayColor()]
let attributedText = NSAttributedString(string: myText as String, attributes: attributes as [NSObject : AnyObject])
cell.textLabel.attributedText = attributedText
cell.textLabel.sizeToFit()
cell.contentView.addSubview(cell.textLabel)
return cell
我想让我的标签文本高度将按钮向下移动,但没有任何反应,我还尝试找出高度并将其发送到单元格,例如:
cell.textHeigth = textHeigth,并在其中使用textHeigth
buttonView.frame = CGRect(x: frame.width/2 - frame.width * 0.4, y: 0 + textHeigth, width: frame.size.width , height: frame.size.height * 0.8)
但后来我得到一些变量为 nil 的错误,但我尝试打印该变量并且在将它发送到 customClass 之前它不是 nil
最佳答案
实现下面的委托(delegate)方法来设置 Collection View 单元格的宽度和高度
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return CGSizeMake(width,height);
}
关于ios - 如何在 CollectionViewCell 中设置元素的框架?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31663063/