Three.jsを使って、作ってみた

プログラミング関連の事を色々書いています(^^) 週末はレストランやコンビニのお菓子のことを書いています。

Swift ボタンを作る  UIButton

今回は、Swiftを使って、ボタンを作る方法を書きます。


具体的に言いますと、UIButtonクラスを使います。
UIButtonクラスは、ボタンを管理するクラスです。


さっそく書いていきます。

こんな感じです↓

 var button = UIButton(frame: CGRectMake(260, 30, 50, 50))
 button.backgroundColor = UIColor(red: 0.0, green: 1.0, blue: 0.0, alpha: 1.0)
 button.addTarget(self, action: "btn:", forControlEvents:.TouchUpInside)
 self.view.addSubview(button)

「btn」関数(※関数名は適宜変えてください。)

func btn(sender: UIButton){       
        println("button push!")
}

実行結果1
f:id:gupuru:20140615225318p:plain
緑色の部分がボタンです。タップすると、printlnで「button push!」と表示します。

実行結果2
f:id:gupuru:20140615225537p:plain


まず、ここの部分でボタンを作っています。

var button = UIButton(frame: CGRectMake(260, 30, 50, 50))

X座標:260,Y座標:30のところに作られます。幅、高さは50です。


次に、こちらの部分で背景色を決めています。

button.backgroundColor = UIColor(red: 0.0, green: 1.0, blue: 0.0, alpha: 1.0)


次に、こちらの部分は、ボタンをクリックした時に「btn」関数を処理する感じです。

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


最後に、 UIButtonのプロパティを少し書きます。

1.キャプション設定

「setTitle」を使うとキャプションの設定ができます。

「 〜.setTitle("◯◯", forState: 〜)」

 var button = UIButton(frame: CGRectMake(160, 30, 100, 50))

        button.setTitle("ぼたん", forState: .Normal)   //追加

        button.backgroundColor = UIColor(red: 0.0, green: 1.0, blue: 0.0, alpha: 1.0)
        button.addTarget(self, action: "btn:", forControlEvents:.TouchUpInside)
        self.view.addSubview(button)

実行結果
f:id:gupuru:20140615231126p:plain


2.キャプションの色を変える

「setTitleColor」を使うとキャプションの色が変えれます。

var button = UIButton(frame: CGRectMake(160, 30, 100, 50))
        button.setTitle("ぼたん", forState: .Normal)

        button.setTitleColor(UIColor.blueColor(), forState: .Normal)   //追加

       button.backgroundColor = UIColor(red: 0.0, green: 1.0, blue: 0.0, alpha: 1.0)
        button.addTarget(self, action: "btn:", forControlEvents:.TouchUpInside)
        self.view.addSubview(button)

実行結果
f:id:gupuru:20140615234012p:plain


3.角丸&枠線をつける

角丸にするには、「cornerRadius」を使うとできます。
枠線は、「borderWidth」を使います。

 var button = UIButton(frame: CGRectMake(160, 30, 100, 50))
        button.setTitle("ぼたん", forState: .Normal)
        button.setTitleColor(UIColor.blueColor(), forState: .Normal)
        
        button.layer.cornerRadius = 10   //角丸
        button.layer.borderWidth = 1     //枠線

        button.addTarget(self, action: "btn:", forControlEvents:.TouchUpInside)
        self.view.addSubview(button)

実行結果
f:id:gupuru:20140615234239p:plain


これで、終わります。


参考サイト
http://toshihiro-oyama.com/swift%E3%81%A7%E3%82%B3%E3%83%BC%E3%83%89%E3%81%A0%E3%81%91%E3%81%A7%E3%83%9C%E3%82%BF%E3%83%B3%E3%81%A8%E3%83%A9%E3%83%99%E3%83%AB%E3%82%92%E4%BD%9C%E3%81%A3%E3%81%A6%E6%96%87%E5%AD%97%E3%82%92/
UIButton - iPhoneアプリ開発の虎の巻