UIButtons setAttributedTitle Disappears After Calling layoutSubviews in UIButton Extension - swift

I had a corner radius problem with all of my UIButtons, but was finally able to resolve the issue by following the solution at (Setting corner radius through viewDidAppear() or viewWillLayoutSubviews()?
) However, now I have "lost" all of my attributed button titles. I have been battling this issue for a couple of weeks and feel like I am very close to figuring it all out. I apologize if this is a poorly phrased question as I am still relatively new to Swift.
Here is the application I am working on:
my default iOS calculator project
In my Swift-file, UIButtonExtension.swift, I have the following:
import Foundation
import UIKit
extension UIButton {
override open func layoutSubviews() {
super.layoutSubviews()
let radius = min(bounds.width, bounds.height) / 2
layer.cornerRadius = radius
}
}
In one of my other Swift-files, myCalculatorViewController.swift, I have:
import UIKit
class myCalculatorViewController: UIViewController {
#IBOutlet weak var tag1_Button: UIButton!
#IBOutlet weak var tag2_Button: UIButton!
#IBOutlet weak var tag3_Button: UIButton!
// .....
#IBOutlet weak var tag19_Button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// main/basic calc button view controller
tag1_Button.titleLabel?.textAlignment = .center
tag1_Button.contentHorizontalAlignment = .center
tag1_Button.titleLabel?.numberOfLines = 1
let str_tag1_Button = NSMutableAttributedString(string: "AC")
str_tag1_Button.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: 10), range: NSMakeRange(0, 2))
str_tag1_Button.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 1.0), range: NSMakeRange(0, 2))
tag1_Button.setAttributedTitle(str_tag1_Button, for: .normal)
tag1_Button.backgroundColor = UIColor(red: 40/255.0, green: 247/255.0, blue: 45/255.0, alpha: 1.0)
// and so forth with the rest of the tag buttons up to tag19_Button that sets title, "="
}
}
Next, in another Swift-file, instantiatedLandscapeButtonViewController, I have a similiar setup for the UIButtons with tag1 to tag30:
import UIKit
class instantiatedLandscapeButtonViewController: UIViewController {
#IBOutlet weak var tag1_Button: UIButton!
#IBOutlet weak var tag2_Button: UIButton!
#IBOutlet weak var tag3_Button: UIButton!
// .....
#IBOutlet weak var tag30_Button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// additional landscape buttons, setup
tag1_Button.titleLabel?.textAlignment = .center
tag1_Button.contentHorizontalAlignment = .center
tag1_Button.titleLabel?.numberOfLines = 1
let str_tag1_Button = NSMutableAttributedString(string: "mc")
str_tag1_Button.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: 10), range: NSMakeRange(0, 2))
str_tag1_Button.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor(red: 251/255.0, green: 251/255.0, blue: 251/255.0, alpha: 1.0), range: NSMakeRange(0, 2))
tag1_Button.setAttributedTitle(str_tag1_Button, for: .normal)
// and so forth
}
}

Your code as it stands is dangerous and illegal:
extension UIButton {
override open func layoutSubviews() {
No! You cannot perform an override in an extension! The results can be unpredictable. The way to achieve a reliable circular button is to subclass UIButton, where override is legal, and use that subclass.
class MyCircularButton: UIButton {
override open func layoutSubviews() {
super.layoutSubviews()
let radius = min(bounds.width, bounds.height) / 2
layer.cornerRadius = radius
}
}
Now use a MyCircularButton instead of a plain UIButton wherever you want a circular button. I don't know that this will solve the issue you're having, but it is certainly a required first step.
I tested your remaining code like this, and it worked fine:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let tag1_Button = MyCircularButton()
tag1_Button.frame = CGRect(x: 100, y: 100, width: 40, height: 40)
tag1_Button.titleLabel?.textAlignment = .center
tag1_Button.contentHorizontalAlignment = .center
tag1_Button.titleLabel?.numberOfLines = 1
let str_tag1_Button = NSMutableAttributedString(string: "AC")
str_tag1_Button.addAttribute(.font, value: UIFont.systemFont(ofSize: 10), range: NSMakeRange(0, 2))
str_tag1_Button.addAttribute(.foregroundColor, value: UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 1.0), range: NSMakeRange(0, 2))
tag1_Button.setAttributedTitle(str_tag1_Button, for: .normal)
tag1_Button.backgroundColor = UIColor(red: 40/255.0, green: 247/255.0, blue: 45/255.0, alpha: 1.0)
self.view.addSubview(tag1_Button)
}
}
Result:

Related

Problem with background in table when emulating Iphone Max Pro 12

I'm trying to emulate my app in different Iphone models but I'm also having the same mistake when I use a Max Pro 12. Anytime I use a tableViewContoller it seems not to fill the background cells completely. Just check my pictures. In the rest of models, including Max Pro 11 it's working ok. I don`t have any constraints because the I can't add them when I use tableViewController. Any suggestion?
Here you have my code.
import UIKit
import FirebaseAuth
class MenuCustomCellController: UITableViewCell {
#IBOutlet weak var imEvento: UIImageView!
#IBOutlet weak var txtNombreEvento: UILabel!
#IBOutlet weak var txtFechaEvento: UILabel!
#IBOutlet weak var txtEstadoEvento: UILabel!
}
class MenuInicialTableController: UITableViewController {
#IBOutlet weak var celdaUsuarios: UITableViewCell!
#IBOutlet weak var celdaEventos: UITableViewCell!
#IBOutlet weak var celdaBuscarEventos: UITableViewCell!
#IBOutlet weak var celdaGraficos: UITableViewCell!
#IBOutlet weak var celdaCerrar: UITableViewCell!
#IBOutlet weak var celdaAyuda: UITableViewCell!
override func viewWillAppear(_ animated: Bool) {
let tap = UITapGestureRecognizer(target: self, action: #selector(MenuInicialTableController.tapFunction))
celdaCerrar.isUserInteractionEnabled = true
celdaCerrar.addGestureRecognizer(tap)
let background = UIView()
tableView.backgroundView = background
tableView.backgroundView?.aplicarFondoDegradado()
tableView.layer.borderWidth = 2
tableView.layer.borderColor = UIColor.white.cgColor
tableView.layer.cornerRadius = 10
celdaUsuarios.layer.borderWidth = 1
celdaUsuarios.layer.borderColor = UIColor.white.cgColor
celdaUsuarios.layer.cornerRadius = 10
celdaUsuarios.contentView.aplicarFondoMenuUsuarios()
celdaEventos.layer.borderWidth = 1
celdaEventos.layer.borderColor = UIColor.white.cgColor
celdaEventos.layer.cornerRadius = 10
celdaEventos.contentView.aplicarFondoMenuEventos()
celdaGraficos.layer.borderWidth = 1
celdaGraficos.layer.borderColor = UIColor.white.cgColor
celdaGraficos.layer.cornerRadius = 10
celdaGraficos.contentView.aplicarFondoMenuEventos()
celdaCerrar.layer.borderWidth = 1
celdaCerrar.layer.borderColor = UIColor.white.cgColor
celdaCerrar.layer.cornerRadius = 10
celdaCerrar.contentView.aplicarFondoMenuUsuarios()
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "MENÚ PRINCIPAL"
self.navigationItem.setHidesBackButton(true, animated: true)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
//Dos filas por sección
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
#objc
func tapFunction(sender:UITapGestureRecognizer) {
exit(0)
}
}
And here you have how I apply gradients:
func aplicarFondoMenuUsuarios() {
let colorInicio = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0).cgColor
let colorFin = UIColor(red: 0/255, green: 190/255, blue: 219/255, alpha: 1.0).cgColor
if let gradientLayer = layer.sublayers?.first as? CAGradientLayer {
gradientLayer.colors = [colorInicio,colorFin]
}
else{
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [colorInicio, colorFin]
gradientLayer.startPoint = CGPoint(x: 0, y: 0.50)
gradientLayer.endPoint = CGPoint(x: 0.50, y: 1.00)
gradientLayer.frame = self.bounds
self.layer.insertSublayer(gradientLayer, at:0)
}
func aplicarFondoMenuEventos() {
let colorInicio = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0).cgColor
let colorFin = UIColor(red: 15/255, green: 0/255, blue: 219/255, alpha: 1.0).cgColor
if let gradientLayer = layer.sublayers?.first as? CAGradientLayer {
gradientLayer.colors = [colorInicio,colorFin]
}
else{
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [colorInicio, colorFin]
gradientLayer.startPoint = CGPoint(x: 0, y: 0.50)
gradientLayer.endPoint = CGPoint(x: 0.50, y: 1.00)
gradientLayer.frame = self.bounds
self.layer.insertSublayer(gradientLayer, at:0)
}
}
Don't use viewWillAppear for layout-code. And not for TapGestures either. Move the three first lines (tap-related) into viewDidLoad, and put the rest into override func viewDidLayoutSubviews(){}.
There are a lot of other stuff you should do as well, like subclassing the cells and have them perform their gradients at the time of their own layout, and you should also remove let background = UIView() and instead just say tableView.backgroundView = UIView() in viewDidLoad (not in willAppear and not in viewDidLayoutSubviews).

How can I get a textview to trigger a scrollview to move up for the keyboard?

I'm creating a form that lives on a view within a scrollview. It contains two textFields and one textView. I've cobbled together some code from online resources(like this one) so that it scrolls up if a textField is ever too low on the view/obstructed by the keyboard. The problem is that it doesn't seem to work for textViews.
I've done my best to comprehend why textViews won't trigger the same behavior, but I could really use some help. Here's my VC code:
import UIKit
class AddAPlaceBasicInfoViewController: UIViewController, UITextFieldDelegate, UITextViewDelegate {
// Outlets
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var categoryTextField: UITextField!
#IBOutlet weak var descriptionTextView: UITextView!
#IBOutlet weak var nextButton: UIButton!
#IBOutlet weak var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(noti:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(noti:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
// Default to an disabled "Next" button.
nextButton.isEnabled = false
nextButton.backgroundColor = UIColor(red: 89/255, green: 89/255, blue: 89/255, alpha: 1/1)
// Check that fields are filled.
nameTextField.delegate = self
descriptionTextView.delegate = self
// Helper functions.
createToolbar()
descriptionTextViewSetup(descriptionTextView)
}
// Creates the done button above the category picker.
func createToolbar() {
// Creates an instance of UIToolbar() named "toolbar".
let toolbar = UIToolbar()
toolbar.sizeToFit()
// Set up button properties.
let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(AddAPlaceBasicInfoViewController.dismissKeyboard))
// Set color to teal.
doneButton.tintColor = UIColor(red: 0/255, green: 134/255, blue: 111/255, alpha: 1)
// Set up button in the toolbar and make it interactive.
toolbar.setItems([doneButton], animated: false)
toolbar.isUserInteractionEnabled = true
// Add the toolbar as an accessory view to the category picker.
nameTextField.inputAccessoryView = toolbar
categoryTextField.inputAccessoryView = toolbar
descriptionTextView.inputAccessoryView = toolbar
// Set toolbar's background to white.
toolbar.backgroundColor = UIColor.white
}
// Function to dismiss the keyboard. Used when the user taps the "Done" button in the toolbar.
func dismissKeyboard() {
view.endEditing(true)
if nameTextField.text?.characters.count == 0 || categoryTextField.text?.characters.count == 0 || descriptionTextView.text == "What's this place like? (You'll be able to add a photo on the next screen)" {
nextButton.isEnabled = false
nextButton.backgroundColor = UIColor(red: 89/255, green: 89/255, blue: 89/255, alpha: 1/1)
} else {
nextButton.isEnabled = true
nextButton.backgroundColor = UIColor(red: 0/255, green: 134/255, blue: 111/255, alpha: 1/1)
}
}
// Function to create placeholder text.
func descriptionTextViewSetup(_ textView: UITextView) {
// Modifications
descriptionTextView.text = "What's this place like? (You'll be able to add a photo on the next screen)"
descriptionTextView.textColor = UIColor(red: 199/255, green: 199/255, blue: 205/255, alpha: 1/1)
descriptionTextView.textContainer.lineFragmentPadding = 0
//descriptionTextView.textColor = UIColor.lightGray
}
//---------------------------------
// MARK: - Notification Center
//---------------------------------
func keyboardWillHide(noti: Notification) {
let contentInsets = UIEdgeInsets.zero
scrollView.contentInset = contentInsets
scrollView.scrollIndicatorInsets = contentInsets
}
func keyboardWillShow(noti: Notification) {
guard let userInfo = noti.userInfo else { return }
guard var keyboardFrame: CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue else { return }
keyboardFrame = self.view.convert(keyboardFrame, from: nil)
var contentInset:UIEdgeInsets = scrollView.contentInset
contentInset.bottom = keyboardFrame.size.height
scrollView.contentInset = contentInset
}
}
If you are creating a Form for users where they can enter information then I would suggest using a static UITableView. Static UITableView can be used if your UIViewController is of type UITableViewController. Static TableView makes it very easy to place controls and since UITableView already has a UIScrollView it automatically scrolls when the UITextView is in focus.
Try it out:

Segue to different categories from Collection View

Edit: I am on the right track, but the button can only point to 1 ViewController
I used
#IBAction func viewTouchedBttn(_ sender: Any) {
print("touched")
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
switch indexPath.row {
case 0:
print("1")
performSegue(withIdentifier: "1", sender: nil)
case 1:
performSegue(withIdentifier: "2", sender: nil)
case 2:
performSegue(withIdentifier: "3", sender: nil)
default:
break
}
}
I recently done the tutorial about building a carousel in swift with a UICollectionView as taught in this tutorial https://www.youtube.com/watch?v=vB-HKnhOgl8 ( you can download it as well so we would have the same basis)
I am quit new to coding so I am sorry if this is quit obvious for you and I don't get it ^^.
Each category should point to a different vc by clicking on the cell.
When I press on the View with "Travel the world" the segue should point to the VC where you can talk about Travel, if I am interested in building apps and click on that view, I want to be directed to this specific category.
Thanks for your help! :)
edit: files
InterestCollectionView
class InterestCollectionViewCell: UICollectionViewCell
{
#IBOutlet weak var featuredImageView: UIImageView!
#IBOutlet weak var interestTitleLabel: UILabel!
#IBOutlet weak var backgroundColorView: UIView!
#IBOutlet weak var kategorie: UILabel!
var interest: Interest? {
didSet {
self.updateUI()
}
}
private func updateUI()
{
if let interest = interest {
kategorie.text = interest.kategorie
featuredImageView.image = interest.featuredImage
interestTitleLabel.text = interest.title
backgroundColorView.backgroundColor = interest.color
} else {
featuredImageView.image = nil
interestTitleLabel.text = nil
backgroundColorView.backgroundColor = nil
}
}
override func layoutSubviews() {
super.layoutSubviews()
self.layer.cornerRadius = 3.0
layer.shadowRadius = 10
layer.shadowOpacity = 0.4
layer.shadowOffset = CGSize(width: 5, height: 10)
self.clipsToBounds = false
}
}
interest file
class Interest
{
// MARK: - Public API
var kategorie = ""
var title = ""
var featuredImage: UIImage
var color: UIColor
init(title: String, featuredImage: UIImage, color: UIColor, kategorie: String)
{
self.kategorie = kategorie
self.title = title
self.featuredImage = featuredImage
self.color = color
}
// MARK: - Private
// dummy data
static func fetchInterests() -> [Interest]
{
return [
Interest(title: "Travelling Around the World", featuredImage: UIImage(named: "f1")!, color: UIColor(red: 63/255.0, green: 71/255.0, blue: 80/255.0, alpha: 0.8), kategorie: "Forum"),
Interest(title: "Cafe with Best Friends", featuredImage: UIImage(named: "f2")!, color: UIColor(red: 240/255.0, green: 133/255.0, blue: 91/255.0, alpha: 0.8), kategorie: "Forum"),
Interest(title: "Study Personal Development Books and Courses", featuredImage: UIImage(named: "f3")!, color: UIColor(red: 105/255.0, green: 80/255.0, blue: 227/255.0, alpha: 0.8), kategorie: "Post"),
Interest(title: "Build Amazing iOS Apps", featuredImage: UIImage(named: "f4")!, color: UIColor(red: 102/255.0, green: 102/255.0, blue: 102/255.0, alpha: 0.8), kategorie: "Forum"),
Interest(title: "Learn. Create. Contribute.", featuredImage: UIImage(named: "f5")!, color: UIColor(red: 245/255.0, green: 62/255.0, blue: 40/255.0, alpha: 0.8),kategorie: "Forum"),
Interest(title: "Inspire, Instruct, and Empower People", featuredImage: UIImage(named: "f6")!, color: UIColor(red: 103/255.0, green: 217/255.0, blue: 87/255.0, alpha: 0.8), kategorie: "Bilder"),
Interest(title: "Business and Marketing Geeks", featuredImage: UIImage(named: "f7")!, color: UIColor(red: 63/255.0, green: 71/255.0, blue: 80/255.0, alpha: 0.8), kategorie: "Forum"),
Interest(title: "3D Printing, Virtual Reality and AI", featuredImage: UIImage(named: "f8")!, color: UIColor(red: 240/255.0, green: 133/255.0, blue: 91/255.0, alpha: 0.8), kategorie: "Forum"),
Interest(title: "Einzeiler", featuredImage: UIImage(named: "f3")!, color: UIColor(red: 30/255.0, green: 20/255.0, blue: 130/255.0, alpha: 0.8), kategorie: "Forum")
]
}
}
the interest ViewController
import UIKit
class InterestsViewController: UIViewController
{
#IBOutlet weak var collectionView: UICollectionView!
var interests = Interest.fetchInterests()
let cellScaling: CGFloat = 0.6
override func viewDidLoad() {
super.viewDidLoad()
let screenSize = UIScreen.main.bounds.size
let cellWidth = floor(screenSize.width * cellScaling)
let cellHeight = floor(screenSize.height * cellScaling)
let insetX = (view.bounds.width - cellWidth) / 2.0
let insetY = (view.bounds.height - cellHeight) / 2.0
let layout = collectionView!.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = CGSize(width: cellWidth, height: cellHeight)
collectionView?.contentInset = UIEdgeInsets(top: insetY, left: insetX, bottom: insetY, right: insetX)
collectionView?.dataSource = self
collectionView?.delegate = self
}
}
extension InterestsViewController : UICollectionViewDataSource
{
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return interests.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "InterestCell", for: indexPath) as! InterestCollectionViewCell
cell.interest = interests[indexPath.item]
return cell
}
}
extension InterestsViewController : UIScrollViewDelegate, UICollectionViewDelegate
{
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>)
{
let layout = self.collectionView?.collectionViewLayout as! UICollectionViewFlowLayout
let cellWidthIncludingSpacing = layout.itemSize.width + layout.minimumLineSpacing
var offset = targetContentOffset.pointee
let index = (offset.x + scrollView.contentInset.left) / cellWidthIncludingSpacing
let roundedIndex = round(index)
offset = CGPoint(x: roundedIndex * cellWidthIncludingSpacing - scrollView.contentInset.left, y: -scrollView.contentInset.top)
targetContentOffset.pointee = offset
}
}
You have multiple options to do what you want.
For example you could add in your storyboard a storyboard reference to controller you want to segue to, or a view controller if it's in the same storyboard. And then ctrl + drag from the view to the view controller (or storyboard reference) that you want to segue to. There you will have the different segues types (show, push, etc).
That's the full storyboard way of doing it.
There are multiple other options. But that may be the easiest.
https://developer.apple.com/library/content/featuredarticles/ViewControllerPGforiPhoneOS/UsingSegues.html
EDIT:
You can also create 8 segues from the controller (ctrl + drag from controller) to other controllers or storyboard references. Then click on the segues created and in the identifier inspector name every segue with a unique identifier.
Then when you click on the cell you can determine which cell was clicked and perform the segue you need for that cell with performSegueWithIdentifier(identifier, sender)

Swift: Text label not updating

I have a text label (NSTextField). I want it to pin to the upper left vertex of every object to show an element's number in UI.
But my label shows only ZERO and doesn't move (it stays in the upper left corner). What I did wrong?
Here is my code in AppDelegate.swift:
import Cocoa
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
#IBOutlet weak var window: NSWindow!
#IBOutlet weak var drawingView: DrawingView!
#IBOutlet weak var label: NSTextField!
var localArray: [CGPoint] = []
func applicationDidFinishLaunching(aNotification: NSNotification) {
label.textColor = NSColor(calibratedRed: 0.15, green: 0, blue: 0.75, alpha: 0.3)
label.font! = NSFont(name: "Arial Bold", size: 60)!
label.backgroundColor = NSColor.clearColor()
label.stringValue = "\(localArray.count/4)"
for (pointIndex, _) in localArray.enumerate() {
let point = CGPoint(x: (localArray[(pointIndex/4)+1].x), y: (localArray[(pointIndex/4)+1].y))
label.sizeToFit()
label.frame = CGRect(origin: point, size: CGSize(width: label.bounds.width, height: label.bounds.height))
}
}
And here is my code in DrawingView.swift:
var delegate = NSApplication.sharedApplication().delegate as! AppDelegate
delegate.localArray = myArray.map { return $0.coordSequence()[0] }
myArray contains cgpoints.
Am I right putting label parameters inside applicationDidFinishLaunching method?
You are trying to update NSTextField probably from wrong thread.
dispatch_async(dispatch_get_main_queue(),{
label.stringValue = "\((localArray.count/4)+1)"
})
Try to investigate you're array i could make assumption that when you set value of the label localArray.count is 0. Also keep in mind that you are working with Int and if localArray.count is 3 so 3/4 will be 0.

UIView is not changing correctly the color values SWIFT

I want my app to start with a color in the view but when I add the UIColor values to the ViewDidLoad I change the color to white! and not the red color I want to add. Here is my code, I have checked all the code but am kind of programming in swift so I don't find something that is not getting the work done:
class RGBViewController: UIViewController {
//Sldiers
#IBOutlet weak var redSlider: UISlider!
#IBOutlet weak var greenSlider: UISlider!
#IBOutlet weak var blueSlider: UISlider!
//Labels
#IBOutlet weak var redLabel: UILabel!
#IBOutlet weak var greenLabel: UILabel!
#IBOutlet weak var blueLabel: UILabel!
//View
#IBOutlet weak var colorView: UIView!
//set the thumb image
func changeThumbImage() {
let redThumb = UIImage(named: "RedSmall")
redSlider?.setThumbImage(redThumb, forState: .Normal)
let greenThumb = UIImage(named: "GreenSmall")
greenSlider?.setThumbImage(greenThumb, forState: .Normal)
let blueThumb = UIImage(named: "BlueSmall")
blueSlider?.setThumbImage(blueThumb, forState: .Normal)
}
//VIEW DID LOAD
override func viewDidLoad() {
super.viewDidLoad()
changeThumbImage()
updateBackgroundColor()
colorView.backgroundColor! = UIColor(red: 226, green: 67, blue: 67, alpha: 1)
}
func colorValues() {
//assign the Int value to the labels
redLabel?.text = String(stringInterpolationSegment: Int(redSlider.value * 255))
greenLabel?.text = String(stringInterpolationSegment: Int(greenSlider.value * 255))
blueLabel?.text = String(stringInterpolationSegment: Int(blueSlider.value * 255))
}
#IBAction func updateBackgroundColor() {
colorValues()
//safe unwrap the sliders and assign the view color
if let red = redSlider, green = greenSlider, blue = blueSlider{
let redValue = CGFloat(red.value)
let greenValue = CGFloat(green.value)
let blueValue = CGFloat(blue.value)
colorView.backgroundColor = UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: 1)
}
}
}
You have to divide the color value with 255
UIColor(red: 226/255.0, green: 67/255.0, blue: 67/255.0, alpha: 1.0)
With your action also :
#IBAction func updateBackgroundColor() {
colorValues()
let redValue = CGFloat(redSlider.value)
let greenValue = CGFloat(greenSlider.value)
let blueValue = CGFloat(blueSlider.value)
colorView.backgroundColor = UIColor(red: redValue/255.0, green: greenValue/255.0, blue: blueValue/255.0, alpha: 1.0)
}
I have created sample :
#IBOutlet var colorView: UIView!
#IBAction func chageSlider(sender: UISlider!) {
println(sender.value)
self.colorView.backgroundColor = UIColor(red: CGFloat(sender.value)/255.0, green: 0.0, blue: 0.0, alpha: 1.0)
}
changeSlider is valueChanged action of the UISlider
Connect your slider with #IBAction
Hope it helps you.