ios - swift 3 : Add UIButton extension to ViewController

标签 ios swift3 uibutton swift-extensions

我是 iOS/Swift 的初学者,正在尝试创建一个没有 Storyboard 的简单应用程序。 我创建了一个 UIButton 扩展,我想在我的 View 中添加一个简单的按钮(约束将在稍后设置)。 不幸的是,该按钮不可见。 如果有人帮助我,我将不胜感激。 谢谢!

--- 按钮.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)

    }
}

最佳答案

试试这个:

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

关于ios - swift 3 : Add UIButton extension to ViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43718510/

相关文章:

android - 在 Waze 或移动版谷歌地图中检测导航结束

swift - 如何在 Swift3 中覆盖 viewWillDisappear

swift - xcode 8 测试版 3 : Expected ',' joining parts of a multi-clause condition

ios - 快速启用/禁用开始和暂停按钮

ios - UIButton 按下时改变状态

ios - 在 iOS 应用程序中将少量数据保存到磁盘的最正确方法是什么?

ios - 隐式转换丢失整数精度 : 'unsigned long' to 'int' - Error

ios - 模块文件是由较新版本的编译器创建的

ios - 调整 UIButton 宽度/高度 (iOS) - 如何在不禁用自动布局的情况下解决?

ios - UIButton 内的奇怪填充