【问题标题】:Swift 3: Add UIButton extension to ViewControllerSwift 3:将 UIButton 扩展添加到 ViewController
【发布时间】:2017-05-01 11:39:54
【问题描述】:

我是 iOS/Swift 的初学者,并试图在没有 Storyboard 的情况下创建一个简单的应用程序。 我创建了一个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)

    }
}

【问题讨论】:

  • 我宁愿建议创建一个自定义初始化程序。

标签: ios swift3 uibutton swift-extensions


【解决方案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
   }
}

【讨论】:

    猜你喜欢
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-12
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    相关资源
    最近更新 更多