Swift 3: Add UIButton extension to ViewController

巧了我就是萌 提交于 2019-12-11 06:06:17

问题


I'm a beginner in iOS/Swift and trying to create a simple application without Storyboard. I created a UIButton extension and I would like to add a simple button to my view (constraints will be set later). Unfortunately the button is not visible. I would appreciate if somebody helps me. Thank you!

--- 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:


Try this:

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
   }
}


来源:https://stackoverflow.com/questions/43718510/swift-3-add-uibutton-extension-to-viewcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!