Tap on UIView and change color itself - uiview

I need to change color of UIView then I tap on it. How I can do this?
P.S. Sorry for my english

here are the steps.
Drag a UIView to your ViewController
Then create an IBOutlet to it. (just drag a connection to your viewcontroller class).
then create gesture for it.
then create an action for it.
assign the action
here is the full code for your view controller
import UIKit
class ViewController: UIViewController {
//Outlet Connection to your View
#IBOutlet weak var myView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
myView.layer.borderColor = UIColor.black.cgColor
myView.layer.borderWidth = 2
let taptoColorGesture = UITapGestureRecognizer.init(target: self, action: #selector(ViewController.changeMyColor))
myView.addGestureRecognizer(taptoColorGesture)
// Do any additional setup after loading the view, typically from a nib.
}
func changeMyColor () {
let colorR : Float = Float(Int(arc4random_uniform(255)))
let colorG : Float = Float(arc4random_uniform(255))
let colorB : Float = Float(arc4random_uniform(255))
let themyColor = UIColor.init(colorLiteralRed: colorR/255, green: colorG/255, blue: colorB/255, alpha: 1.0)
myView.backgroundColor = themyColor
//this function creates random color each time
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
and here is the project url to github Change the UIView Color on tap in Swift

// first go to identity inspector and set 'user interaction enabled' on the view
// Then put this in the viewDidLoad method (change :myExampleView to your view name)
let tapChangeColor = UITapGestureRecognizer(target: self, action: #selector(changeColor))
self.myExampleView.addGestureRecognizer(tapChangeColor)
// put this method somewhere in ViewController class:
func changeColor() {
self.myExampleView.backgroundColor=UIColor.blue
}

Related

Why does a UIBarButtonItem action not trigger in a separate class?

I wrote a class that shall handle UIBarButtonItem taps.
The initializer takes a reference to an UINavigationItem. All buttons etc. are attached to this UINavigationItem. I tried to connect them with actions (didPressMenuItem()), but when I click the button, the action is not triggered (nothing is written to the console nor the breakpoint I set is triggered).
How can I link the UIBarButtonItem to the function defined in this class?
internal final class NavigationBarHandler {
// MARK: Properties
private final var navigationItem: UINavigationItem?
// MARK: Initializers
required init(navigationItem: UINavigationItem?) {
self.navigationItem = navigationItem
}
internal final func setupNavigationBar() {
if let navigationItem = navigationItem {
let menuImage = UIImage(named: "menu")?.withRenderingMode(.alwaysTemplate)
let menuItem = UIBarButtonItem(image: menuImage, style: .plain, target: self, action: #selector(didPressMenuItem(sender:)))
menuItem.tintColor = .white
navigationItem.leftBarButtonItem = menuItem
}
}
#objc func didPressMenuItem(sender: UIBarButtonItem) {
print("pressed")
}
}
This is what happens in the view controller to which navigationItem the buttons etc. are attached.
class ContactsController: UIViewController {
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .red
self.title = "Kontakte"
let navigationBarHandler = NavigationBarHandler(navigationItem: self.navigationItem)
navigationBarHandler.setupNavigationBar()
}
}
Th problem here is that you're instantiating NavigationBarHandler inside viewDidload() which is why the memory reference dies after viewDidLoad() finishes. What you should do is to create the variable outside like this.
class ContactsController: UIViewController {
var navigationBarHandler: NavigationBarHandler!
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .red
self.title = "Kontakte"
self.navigationBarHandler = NavigationBarHandler(navigationItem: self.navigationItem)
navigationBarHandler.setupNavigationBar()
}
}
This way the memory reference stays.

Delegation between two ViewControllers without segues

I am learning the concept of delegation and I am stuck in my project. I believe the solution is simple, but as this is something new for me I have no idea what is wrong.
Project concept is simple:
There are two views in the application. In the first view you press the button "change the color" and as a result second view appears. In the second view there are three text fields where user puts numbers respectively for R G and B values in RGB color. When the button is tapped, second view disappears and the first view's background should be changed with color based on the user's input. I assume that the user put correct numbers, therefore at this moment I use forced unwrapping for those values.
At this moment views appear correctly, but the background color of the first view does not change and I have no idea why.
Beneath is the code for two view controllers. I will appreciate any hints.
First VC: ViewController.swift
class ViewController: UIViewController, ColorChangeDelegate {
let secondStoryboard = UIStoryboard(name: "Second", bundle: nil).instantiateViewControllerWithIdentifier("SecondViewController") as UIViewController
var secondVC = SecondViewController()
#IBAction func changeColourButtonTapped(sender: UIButton) {
presentViewController(secondStoryboard, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
secondVC.colorDelegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func didChangeColor(controller: SecondViewController, color: UIColor) {
self.view.backgroundColor = color
}
}
and second VC: SecondViewController.swift
protocol ColorChangeDelegate {
func didChangeColor(controller: SecondViewController, color: UIColor)
}
class SecondViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var myRTextField: UITextField!
#IBOutlet weak var myGTextField: UITextField!
#IBOutlet weak var myBTextField: UITextField!
var colorDelegate : ColorChangeDelegate?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
myRTextField.delegate = self
myGTextField.delegate = self
myBTextField.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldDidBeginEditing(textField: UITextField) {
textField.becomeFirstResponder()
}
#IBAction func goButtonTapped(sender: UIButton) {
let r = Int(myRTextField.text!)!
let g = Int(myGTextField.text!)!
let b = Int(myBTextField.text!)!
let color = UIColor(red: CGFloat(r), green: CGFloat(g), blue: CGFloat(b), alpha: 1.0)
self.view.endEditing(true)
colorDelegate?.didChangeColor(self, color: color)
presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
}
}
You are assigning your delegate to secondVC but the view controller that is actually being presented is in secondStoryboard, so you should set the colorDelegate property of secondStoryboard.

Where to define views, constraints and targets when not using the StoryBoard?

I did some research but I could not find an appropriate answer regarding the following question.
I don't use the interface builder to generate my views so every control is defined programmatically like so :
let loginButton: UIButton = {
let button = UIBUtton()
button.setTitle("Title", forState: .Normal)
// adding some properties to my button
return button
}()
Then I add it to the view of my ViewController like that :
self.view.addSubview(loginButton)
And I add some constraints with the Visual Format Language
For example :
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat
_("V:|[v0(25)]|", options:NSLayoutFormatOptions(), metrics: nil,
_views: ["v0":loginButton]))
It works really well and I prefer it that way(over the IB) but the main issue is that I end up with really big ViewController classes as I define every controls in the ViewControllers classes.
I guess I should have all the controls declarations, constraints,... in a separate file but I can't find how to do that.
I tried to create a separate class, for example LoginView, which contains all the controls, and a function setupViews(superView: UIView) that adds subviews to the superView parameter and specify constraints. Then in the viewDidLoad() method of my ViewController, I instantiate this class (LoginView) and execute the setupView(superView: self.view). It looks like this :
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let loginView = LoginView()
loginView.setupViews(self.view)
}
}
I am pretty sure this is not the way to go. It also causes problems when I try to addTarget to some of my controls.
My question, what is the best way to do it, following the MVC pattern.
Thank you very much !
EDIT 1 :
As asked in the comments, here is the implementation of the LoginView class (I only kept few controls/constraints to keep it short but it is the same process for every other one)
import UIKit
class LoginView {
let superView: UIView?
init(tempSuperView: UIView){
superView = tempSuperView
}
let usernameTextField: UITextField = {
let textField = UITextField()
textField.translatesAutoresizingMaskIntoConstraints = false
textField.textColor = UIColor.whiteColor()
return textField
}()
let loginButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("Login", forState: .Normal)
return button
}()
//some more controls definition
func setupViews() -> Void {
superView!.addSubview(usernameTextField)
superView!.addSubview(loginButton)
superView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat
_("V:|-150-[v0(50)]", options:NSLayoutFormatOptions(), metrics: nil,
_views: ["v0":usernameTextField]))
superView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat
_("H:|-150-[v0(25)]", options:NSLayoutFormatOptions(), metrics: nil,
_views: ["v0":usernameTextField]))
//same for the button
}
}
Here is my ViewController :
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let loginView = LoginView(tempSuperView: self.view)
loginView.setupViews()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

Create a PopUp in Swift using a custom UIView

I am trying to create a custom UIView and display it as a pop up in my main View using Swift.
My Custom UIView code is
class DatePopUpView: UIView {
var uiView:UIView?
override init() {
super.init()
self.uiView = NSBundle.mainBundle().loadNibNamed("DatePopUpView", owner: self, options: nil)[0] as? UIView
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
required override init(frame: CGRect) {
super.init(frame: frame)
}
}
And I am Calling it in my main view as:
#IBAction func date_button_pressed (sender : AnyObject?) {
var popUpView = DatePopUpView()
var centre : CGPoint = CGPoint(x: self.view.center.x, y: self.view.center.y)
popUpView.center = centre
popUpView.layer.cornerRadius = 10.0
let trans = CGAffineTransformScale(popUpView.transform, 0.01, 0.01)
popUpView.transform = trans
self.view .addSubview(popUpView)
UIView .animateWithDuration(0.5, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
popUpView.transform = CGAffineTransformScale(popUpView.transform, 100.0, 100.0)
}, completion: {
(value: Bool) in
})
}
But popUp is not Coming. I used breakpoint and noticed that value is getting assigned to my popUpView but still it is not displayed on my main View. Please Help
Please Note: I am using StoryBoard for my mainView and custom View i have made using xib.
Without additional description on what you are attempting to do, may I suggest something like the code below? Basically, you can use .hidden feature of a view (or any other control) to show/hide the view. You can set the size and positioning of the view to be popped by using the layout editor.
import UIKit
class ViewController: UIViewController {
var popped = false
var popupBtnTitle = "Show Popup"
#IBAction func popupButton(sender: UIButton) {
popped = !popped
anotherView.hidden = !popped
popupBtnTitle = popped ? "Hide Popup" : "Show Popup"
popupButtonOutlet.setTitle(popupBtnTitle, forState: UIControlState.Normal)
}
#IBOutlet weak var popupButtonOutlet: UIButton!
#IBOutlet weak var anotherView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
popped = false
anotherView.hidden = !popped
popupButtonOutlet.setTitle(popupBtnTitle, forState: UIControlState.Normal)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

UIBarButtonItem with customView (UISwitch) disappears shortly after creating the toolbar (even though it's a really simple code!)

I try to create a toolbar with a UIBarButtonItem with a customView (UISwitch). This is done by my function "createtoolbar()".
On viewDidLoad() the toolbar is created properly.
BUT: Creating the toolbar by pressing a Button, the UISwitch disappears approx. 0.1 seconds later.
Hope someone can help me! :)
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
createtoolbar()
}
#IBOutlet var bottomBar: UIToolbar!
let alarmSwitch = UISwitch()
func createtoolbar() {
alarmSwitch.on = true
let alarmSwitchBarButton = UIBarButtonItem(customView: alarmSwitch)
var toolbarbuttons = [alarmSwitchBarButton]
bottomBar.setItems(toolbarbuttons, animated: true)
}
#IBAction func createtoolbarButtonPressed(sender: AnyObject) {
createtoolbar()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
It's unclear what you're trying to do. You're creating the bar button item in code but adding a switch that's an IBOutlet? You can't do that -- if your switch actually is an IBOutlet, then it will already be the subview of some other view, and you can't use it in you bar button. If it's not an IBOutlet (which to shouldn't be), then you need to create the switch in code.

Resources