2016-02-08 2 views
0

Я пытаюсь создать ячейку программно, не используя рассказ, но я натыкаюсь на некоторые проблемы. Код ячейки следующий.Программа UICollectionViewCell Programmatically

import UIKit 

class ProductCategoryCollectionViewCell: UICollectionViewCell { 


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


var productCategoryImageView :UIImageView! 

func setupCell(){ 
    //seting up the imageView as subView 
    productCategoryImageView = UIImageView() 
    productCategoryImageView.translatesAutoresizingMaskIntoConstraints = false 
    let subViewDictionary = ["productCategoryImageViewKey" : productCategoryImageView] 


    let productCategoryImageViewWidth = contentView.bounds.size.width 
    let productCategoryImageViewHeight = contentView.bounds.size.height 
    let productCategoryImageViewHorizontalConstrain = NSLayoutConstraint.constraintsWithVisualFormat("H:[productCategoryImageViewKey(\(productCategoryImageViewWidth))]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: subViewDictionary) 
    let productCategoryImageViewVerticalConstrain = NSLayoutConstraint.constraintsWithVisualFormat("V:[productCategoryImageViewKey(\(productCategoryImageViewHeight))]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: subViewDictionary) 

    productCategoryImageView.addConstraints(productCategoryImageViewHorizontalConstrain) 


    productCategoryImageView.addConstraints(productCategoryImageViewVerticalConstrain) 



    contentView.addSubview(productCategoryImageView) 
    contentView.backgroundColor = UIColor(red: 1, green: 0, blue: 0, alpha: 0.4) 
} 

}

Я пытаюсь создать subImageView, который будет размер ячейки, однако, не масштабироваться до до размера ячейки.

ответ

0

Размер ячейки не известно, когда метод инициализации называется. Поэтому настройка ширины и высоты на contentView.bounds.size.width и contentView.bounds.size.height не будет работать.

Вместо добавления ограничений для горизонтальных и вертикальных размеров вы можете добавить влево, вправо, вверх и вниз ограничений, как это:

let productCategoryImageViewHorizontalConstrain = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[productCategoryImageViewKey]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: subViewDictionary) 
let productCategoryImageViewVerticalConstrain = NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[productCategoryImageViewKey]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: subViewDictionary) 

И вы должны также вызвать contentView.addSubview(productCategoryImageView) перед добавлением ограничений.

+0

Спасибо ... Почему я не подумал об этом. спасибо – progammingBeignner

-1

/* создать UICollectionView Cell в качестве программно выше код */

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 

    self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 

    UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init]; 
    uicollection=[[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout]; 
    [uicollection setDataSource:self]; 
    [uicollection setDelegate:self]; 

    [uicollection registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"]; 
    [uicollection setBackgroundColor:[UIColor redColor]]; 

    [self.view addSubview:uicollection]; 


    // Do any additional setup after loading the view, typically from a nib. 
} 

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section 
{ 
    return 15; 
} 

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: 
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath]; 
    cell.backgroundColor=[UIColor greenColor]; 

    return cell; 
} 

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    return CGSizeMake(50, 50); 
} 


- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

@end 
+0

Я не понимаю, что вы пытаетесь сделать. У меня уже есть UIcollectionViewControl, и я вызвал методы делегата itemforSize, чтобы масштабировать его до определенного размера. Тем не менее, subImage в ячейке не масштабируется до размера ячейки. – progammingBeignner

+0

Вопрос помечен как «Swift», а не «Objective-C». – Moritz

Смежные вопросы