2017-01-12 6 views
2

私はカスタムセルを含むコレクションビューを持っています。そして、私は、セルがビューの中央に置かれているときに、コレクションビューのUILabelを黒から赤の色に変更する方法については疑問を持っていません。中心位置のときにUICollectionViewCellにマスクを追加します。

enter image description here

+0

あなたが既に試したことをより詳細に示してください(コード)。 – shallowThought

答えて

1

私は考えることができる最も簡単な方法:

import UIKit 

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { 
    @IBOutlet weak var tableView: UITableView! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") 
     tableView.delegate = self 
     tableView.dataSource = self 
    } 


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return 50 
    } 

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) 
     cell.textLabel?.text = "Cell #\(indexPath.row)" 
     return cell 
    } 

    func scrollViewDidScroll(_ scrollView: UIScrollView) { 
     if let tableView = scrollView as? UITableView { 
      for cell in tableView.visibleCells { 
       adjustCellColor(cell: cell) 
      } 
     } 
    } 

    func adjustCellColor(cell: UITableViewCell) { 
     let cellFrame = tableView.convert(cell.frame, to: view) 
     if cellFrame.contains(view.center) { 
      cell.textLabel?.textColor = UIColor.red 
     } else { 
      cell.textLabel?.textColor = UIColor.black 
     } 
    } 
} 

あなたのビューコントローラがあるときにUITableViewUIScrollViewのサブクラスである(とUITableViewDelegateプロトコルがUIScrollViewDelegateプロトコルから継承)ことを覚えておいてくださいUITableViewの代理人func scrollViewDidScroll(_ scrollView: UIScrollView)のようなUIScrollViewDelegateメソッドを実装することができます。このメソッドは、テーブルビューをスクロールするときに呼び出されます。表示されているすべてのセルを反復処理し、セルがビューの中央にある場合は赤に、それ以外の場合は黒にテキストの色を設定します。

関連する問題