2017-05-01 61 views
1

我在的iOS /斯威夫特一個初學者,並試圖建立一個沒有故事板的簡單應用程序。 我創建了一個UIButton擴展,我想添加一個簡單的按鈕到我的視圖(約束將在稍後設置)。 不幸的是,按鈕是不可見的。 如果有人可以幫助我,我將不勝感激。 謝謝!斯威夫特3:UIButton的擴展添加視圖控制器

--- Buttons.swift ---

extension UIButton { 

func createRectangleButton(buttonPositionX: Double, buttonPositionY: Double ,buttonWidth: Double, buttonHeight: Double, buttonTilte: String) { 
    let button = UIButton(type: .system) as UIButton 
    button.frame = CGRect(x: buttonPositionX, y: buttonPositionY, width: buttonWidth, height: buttonHeight) 
    button.setTitle(buttonTilte, for: .normal) 
    button.backgroundColor = COLOR_WHITE 
    button.tintColor = COLOR_BLACK 
    } 
} 

--- InitialViewController.swift ---

import UIKit 

class InitialViewController: BaseViewController { 

override func viewDidLoad() { 
    super.viewDidLoad() 

    // Gradient Layer 
    view.addGradientBackground(colorTop: COLOR_ROYALRED2, colorBottom: COLOR_ROYALRED1) 

    // Button 
    let startButton = UIButton() 
    startButton.createRectangleButton(buttonPositionX: 50, buttonPositionY: 20, buttonWidth: 200, buttonHeight: 50, buttonTilte: "START") 
    self.view.addSubview(startButton) 

    } 
} 
+1

我寧願建議創建一個自定義的初始IZER。 –

回答

1

如下試試這個:

在這裏輸入的代碼

extension UIButton { 

func createRectangleButton(buttonPositionX: Double, buttonPositionY: Double ,buttonWidth: Double, buttonHeight: Double, buttonTilte: String) { 
       let button = self // changes made here 
       button.frame = CGRect(x: buttonPositionX, y: buttonPositionY, width: buttonWidth, height: buttonHeight) 
       button.setTitle(buttonTilte, for: .normal) 
       button.backgroundColor = COLOR_WHITE 
       button.tintColor = COLOR_BLACK 
      } 
+0

作品!非常感謝你! :) –

+0

酷!歡迎。 – KKRocks

+0

這是接受的答案? – KKRocks