LoginSignup
9
8

More than 5 years have passed since last update.

備忘メモ Swiftでtableviewの明細行にボタンを追加して他の画面に遷移する

Last updated at Posted at 2016-04-01

久しぶりに実装し、結構はまったので備忘がてら残します。

buttonをプログラムで実装して、TableViewのCellに追加

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

        let button : UIButton = UIButton.init(type: UIButtonType.Custom) as UIButton
        button.frame = CGRectMake(40, 60, 100, 24)
        let cellHeight: CGFloat = 44.0
        button.center = CGPoint(x: view.bounds.width / 2.0, y: cellHeight / 2.0)
        button.backgroundColor = UIColor.redColor()
        button.addTarget(self, action: #selector(ViewController.buttonClicked(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        button.tag = indexPath.row
        button.setTitle("Click Me !", forState: UIControlState.Normal)

        cell.addSubview(button)

        return cell
    }

ボタンがクリックされた時に、他の画面に遷移する

    @IBAction func buttonClicked(sender: AnyObject) {
        print("clicked")

        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

        let nextViewController = storyBoard.instantiateViewControllerWithIdentifier("NextViewController") 
        self.presentViewController(nextViewController, animated:true, completion:nil)
    }

Objective-CからSwiftになったからといって、この辺の書きっぷりが抜本的に変わったわけではないことを痛感しました。しょぼん。。

追加されるボタンイメージ

スクリーンショット 2016-04-01 16.43.01.png

9
8
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
9
8