Swift 3:向 ViewController 添加 UIButton 扩展

编程入门 行业动态 更新时间:2024-10-28 01:14:11
本文介绍了Swift 3:向 ViewController 添加 UIButton 扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

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

--- 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:向 ViewController 添加 UIButton 扩展

本文发布于:2023-07-16 07:30:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1119378.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Swift   ViewController   UIButton

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!