2017-10-23 5 views
0

私はこのような私のUIViewsの勾配を使用しています:私は、セルを選択するか、セルの選択を解除するときクリック時にコレクションビューのセルまたはボタンのグラデーションを変更するにはどうすればよいですか?

//the cells gradient colors 
    cellgradient.frame = cell.imageView.bounds 
    cellgradient.cornerRadius = cellgradient.frame.height/2 
    cellgradient.colors = [UIColor(hexString: "#ef473a")!, UIColor(hexString: "#cb2d3e")!].map { $0.cgColor } 
    cellgradient.startPoint = CGPoint(x: 0.0, y: 0.5) 
    cellgradient.endPoint = CGPoint(x: 1.0, y: 0.5) 
    cellgradient.colors = [UIColor(hexString: "#ef473a")!, UIColor(hexString: "#cb2d3e")!] 
    cell.imageView.layer.insertSublayer(cellgradient, at: 0) 

は今、私は現在のグラデーションを変更したいです。これはどうすればいいですか?

class CollectionViewCell : UICollectionViewCell 
{ 

@IBOutlet weak var nameLabel: UILabel! 
@IBOutlet weak var imageView: UIImageView! 
public var checked = false 
public var animated = false 
public var cellgradient: CAGradientLayer = CAGradientLayer() 

override var bounds : CGRect { 
    didSet { 
     self.layoutIfNeeded() 
    } 
} 

override var isSelected: Bool { 
    didSet { 
     if isSelected { 
      cellgradient.colors = [UIColor(hexString: "#ef473a")!, UIColor(hexString: "#cb2d3e")!].map { $0.cgColor } 
     } else { 
      cellgradient.colors = [UIColor(hexString: "#29a1e2")! , UIColor(hexString: "#485ac8")!].map { $0.cgColor } 
     } 
    } 
} 
func addthegradientLayer() { 

    //the cells gradient colors 
    cellgradient.frame = imageView.bounds 
    cellgradient.cornerRadius = cellgradient.frame.height/2 
    cellgradient.colors = cellgradient.colors = [UIColor(hexString: "#29a1e2")! , UIColor(hexString: "#485ac8")!].map { $0.cgColor } 
    cellgradient.startPoint = CGPoint(x: 0.0, y: 0.5) 
    cellgradient.endPoint = CGPoint(x: 1.0, y: 0.5) 
    imageView.layer.insertSublayer(cellgradient, at: 0) 
} 

そして、それは動作します:私は次のようでした回答に基づいて

EDIT

。今私はただ1つの問題が残っています: セルの画像ビューがグラデーションの背後に隠れています。 これをどのように解決すればよいですか?

+0

をあなたの層を挿入することができれば、あなたはもう少しあなたのビュー階層を説明してもらえますか?コレクションビューのセルにUIImageViewがあり、CAGradientLayerをイメージビューのレイヤーに追加しているようです。そうですか? –

+0

正確には何をしているのですか – Mike

答えて

0

私はsubclassing UICollectionViewCellでこれを行います。カスタムセルクラスには、グラデーションレイヤを参照するプロパティがあります。

セルのイニシャライザで、今のようにグラデーションレイヤーをイメージビューに追加します。 Then, override the isSelected property's didSetを選択し、選択した状態または標準状態のグラディエントレイヤーを変更します。

+0

私の編集を見ましたが、うまくいきませんでした。 – Mike

+0

@yarnによると、選択した状態と通常の状態の両方で同じ正確な色を使用したようです。 –

+0

さて、それは今、私の唯一の問題は、画像ビューが非表示になっています。 – Mike

0

色の16進文字列は、didSet {}のisSelectedと!isSelecetの両方で同じです。

+0

@Moritz上記のuser8533118のコメントから、なぜ勾配の変更がなかったのかの元の質問に答えたようです。 – Yarn

0

現在のコンセントの下または後

imageView.layer.insertSublayer(cellgradient, below: nameLabel.layer) 
関連する問題