LoginSignup
79
73

More than 5 years have passed since last update.

swiftでUIButtonの見た目を変更するのってCSSで変更するのと比べてすごい面倒ですよね。
今人的には全部覚える必要は無いと思いますが、必要に応じて使って貰えたらと思います。

スクリーンショット 2015-12-09 18.57.22.png
スクリーンショット 2015-12-09 18.56.08.png

スタイルの変更方法

ボタンに表示される文字

button.setTitle("UIButton", forState: .Normal)

文字色 color

button.setTitleColor(UIColor.whiteColor(), forState: .Normal)

タップした状態のテキスト

button.setTitle("押されたよ", forState: .Highlighted)

タップした後の文字色

button.setTitleColor(UIColor.redColor(), forState: .Highlighted)

ボタンのサイズ width height

button.frame = CGRectMake(0, 0, 300, 50)

タグ番号

button.tag = 1

配置場所

button.layer.position = CGPoint(x: self.view.frame.width/2, y:100)

背景色 background-color

button.backgroundColor = UIColor(red:59/255,green:89/255,blue:152/255,alpha:0.7)

角の丸み border-radius

button.layer.cornerRadius = 10

ボーダー幅 border

button.layer.borderWidth = 1

ボーダーの色 border-color

button.layer.borderColor = UIColor(red:1.0,green:1.0,blue:1.0,alpha:0.3).CGColor

ボタンをタップした時に実行するメソッドを指定

button.addTarget(self, action: "tapped:", forControlEvents:.TouchUpInside)

 

    let button = UIButton()
    //ボタンのテキスト
    button.setTitle("UIButton", forState: .Normal)

    //テキストの色 color
    button.setTitleColor(UIColor.whiteColor(), forState: .Normal)

    //タップした状態のテキスト
    button.setTitle("押されたよ", forState: .Highlighted)

    //タップした後の文字色
    button.setTitleColor(UIColor.redColor(), forState: .Highlighted)

    //ボタンのサイズ width height
    button.frame = CGRectMake(0, 0, 300, 50)

    //タグ番号
    button.tag = 1

    //配置場所
    button.layer.position = CGPoint(x: self.view.frame.width/2, y:100)

    //背景色 background-color
    button.backgroundColor = UIColor(red:59/255,green:89/255,blue:152/255,alpha:0.7)


    //角の丸み border-radius
    button.layer.cornerRadius = 10

    //ボーダー幅 border
    button.layer.borderWidth = 1

    //ボーダーの色 border-color
    button.layer.borderColor = UIColor(red:1.0,green:1.0,blue:1.0,alpha:0.3).CGColor

    //ボタンをタップした時に実行するメソッドを指定
    button.addTarget(self, action: "tapped:", forControlEvents:.TouchUpInside)

    //viewにボタンを追加する
    self.view.addSubview(button)

見本

今回はswiftファイルでUIButtonをインスタンス化して使用しましたが、storyboardからボタンを生成してスタイル変更することもできます。
スクリーンショット 2015-12-09 18.57.22.png
スクリーンショット 2015-12-09 18.56.08.png

79
73
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
79
73