Skip to content

Instantly share code, notes, and snippets.

@SuperShinyEyes
Created August 16, 2017 08:30
Show Gist options
  • Save SuperShinyEyes/5b308b25a9fe8f4c76315145a2e9453b to your computer and use it in GitHub Desktop.
Save SuperShinyEyes/5b308b25a9fe8f4c76315145a2e9453b to your computer and use it in GitHub Desktop.
Create UIButton programmatically swift
//
// MainView.swift
// SeyoungARBasic
//
// Created by YOUNG on 16/08/2017.
// Copyright © 2017 YOUNG. All rights reserved.
//
import UIKit
/// View for MainViewController
class MainView: UIView {
var resetButton: UIButton!
let buttonHeight:CGFloat = 100
override init(frame: CGRect) {
super.init(frame: frame)
}
convenience init(frame: CGRect, targetViewController target: UIViewController, resetSelector: Selector) {
self.init(frame: frame)
/// Create resetButton
let resetButtonRect = CGRect(
x: Constants.screenWidth/2,
y: Constants.screenHeight - buttonHeight,
width: Constants.screenWidth/2,
height: buttonHeight
)
resetButton = UIButton(frame: resetButtonRect)
createButton(
button: resetButton,
backgroundColor: UIColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 0.5),
titleColor: .blue,
title: "Reset",
target: target,
selector: resetSelector
)
}
required init?(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
func createButton(
button: UIButton,
backgroundColor: UIColor,
titleColor: UIColor,
title: String,
state: UIControlState = .normal,
target: UIViewController,
selector: Selector
) {
button.setTitle(title, for: state)
button.backgroundColor = backgroundColor
button.setTitleColor(titleColor, for: state)
button.setTitleColor(.black, for: .highlighted)
button.titleLabel?.font = button.titleLabel?.font.withSize(30)
button.addTarget(target, action: selector, for: .touchUpInside)
self.addSubview(button)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment