Swift 3:将UIButton扩展添加到ViewController
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Swift 3:将UIButton扩展添加到ViewController相关的知识,希望对你有一定的参考价值。
我是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)
}
}
答案
试试如下:
在此处输入代码
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
}
以上是关于Swift 3:将UIButton扩展添加到ViewController的主要内容,如果未能解决你的问题,请参考以下文章
如何从 HTTP 请求将图像加载到 UIButton Swift
如何将 UIButton 添加到 Swift Playground?