2012-10-29 24 views
30

Khi xây dựng một ứng dụng iPad, làm thế nào bạn có thể vẽ một đường viền xung quanh một UICollectionViewCell?UICollectionViewCell Border/Shadow

Thêm chi tiết: Tôi đã triển khai lớp ProductCell mở rộng UICollectionViewCell. Bây giờ, tôi muốn chỉ định một số chi tiết ưa thích, ví dụ: một đường viền, bóng tối, vv Tuy nhiên, khi cố gắng sử dụng một cái gì đó như this here, Xcode nói với tôi rằng kiểu người nhận 'CALayer' là một tờ khai chuyển tiếp.

Trả lời

71

Chỉ cần thực hiện nhiều hơn một chút:

#import <QuartzCore/QuartzCore.h> 

trong your.m

Hãy chắc chắn rằng lớp học của bạn triển khai

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath; 

vì đây là nơi thiết lập ô.

Bạn có thể sau đó thay đổi cell.layer.background (chỉ có sẵn khi thạch anh được nhập khẩu)

Xem dưới đây

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath { 
    MyCollectionViewCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"pressieCell" forIndexPath:indexPath]; 
    //other cell setup here 

    cell.layer.borderWidth=1.0f; 
    cell.layer.borderColor=[UIColor blueColor].CGColor; 

    return cell; 
} 
7

Bạn cần phải bao gồm khuôn khổ QuartzCore và nhập tiêu đề vào lớp học của bạn:

#import <QuartzCore/QuartzCore.h> 
11

Swift

Cập nhật cho Swift 3

Giả sử bạn có Collection View set up with the required methods của bạn , bạn chỉ có thể viết một vài dòng mã để thêm đường viền.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell 
    cell.myLabel.text = self.items[indexPath.item] 
    cell.backgroundColor = UIColor.cyan 

    // add a border 
    cell.layer.borderColor = UIColor.black.cgColor 
    cell.layer.borderWidth = 1 
    cell.layer.cornerRadius = 8 // optional 

    return cell 
} 

Ghi chú

  • Nó không phải là cần thiết để nhập khẩu QuartzCore trong Swift nếu bạn đã nhập UIKit.
  • Nếu bạn cũng muốn thêm bóng, hãy xem this answer.
Các vấn đề liên quan