2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Swift4] SegmentControllとTableViewを使ってみる

Posted at

#SegmentControllを使ってみた
備忘録です。内容はそんなにない
iPhoneアプリでよく見るあの画面切り替えてるボタンなんぞやって思って探して昨日を使ってみました。
item名としましてはSegmented Control
説明にはDisplays multiple segments,each of which functions as a discrete buttonと書かれている。
選択肢の中からひとつだけを選択できるボタン、ようするにradio buttonですね。

##一度つまずいたところ
StoryboradにSegmentControlを接続するときsnder: AnyにするのではなくUISegmentedControlにしないとsender.selectedSegmentIndexを使用できないことに注意すること。

UISegmentedControl
@IBAction func segmentButton(_ sender: UISegmentedControl) {
        switch sender.selectedSegmentIndex {
        case 0:viewTable = fruit
        case 1:viewTable = fish
        default:break
        }
        tableView.reloadData()
    }

###全体のソースコード

ViewController全体のソースコード
class ViewController: UIViewController, UITableViewDelegate,UITableViewDataSource {
    
    var fruit = ["りんご","ばなな","いちご","なし","もも"]
    var fish = ["サンマ","アジ","サバ","マグロ","カツオ","タイ"]
    var viewTable: [String] = []

    @IBOutlet weak var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //tableView.delegate = self
        viewTable = fruit
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewTable.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let newCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        newCell.textLabel?.text = viewTable[indexPath.row]
        return newCell
    }

    @IBAction func segmentButton(_ sender: UISegmentedControl) {
        switch sender.selectedSegmentIndex {
        case 0:viewTable = fruit
        case 1:viewTable = fish
        default:break
        }
        tableView.reloadData()
    }
}
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?