I am new in swift.
I have created dynamic button by pressing another button in the same viewController with following code:
#IBAction func yenibtn(sender: AnyObject) {
let btn = UIButton()
btn.frame = CGRectMake(10, 10, 50, 50) //set frame
btn.setTitle("btn", forState: .Normal) //set button title
btn.setTitleColor(UIColor.redColor(), forState: .Normal) //set button title color
btn.backgroundColor = UIColor.greenColor() //set button background color
btn.tag = 1 // set button tag
btn.addTarget(self, action: "btnclicked:", forControlEvents: .TouchUpInside) //add button action
self.view.addSubview(btn) //add button in view
}
func clickMe(sender:UIButton!)
{
print("Button Clicked")
}
and I created second viewController and navigate by performSegueWithIdentifier function. When i call back the previous controller the dynamic object disappears. Is there a way to retain dynamic button during reload of the previous ViewController?
Just use this:
var btn:UIButton!
#IBAction func yenibtn(sender: AnyObject) {
btn= UIButton()
btn.frame = CGRectMake(10, 10, 50, 50) //set frame
///... your code
}
UPDATE
Using your code in the second viewcontroller to close
#IBAction func basgeri(sender: AnyObject) {
performSegueWithIdentifier("bir", sender: self)
}
thinking "I'm closing the viewcontroller", BUT YOU ARE WRONG! You create a new ViewController! You are not returning to the previous one!
To fix it use this:
#IBAction func basgeri(sender: AnyObject) {
presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
}
Related
I would like to titleColor of my UIBUtton to change when the user taps on the button, with the below code currently the color of the UIBUtton title changes if the user press and hold on the button, however, not when tapped quickly, could you please let me know what do I need to change in the below code to make the titleColor change upon a tap detection only:
var resetFiltersButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Clear Filters", for: .normal)
button.titleLabel?.font = UIFont(name: "AppleSDGothicNeo-Bold", size: 20)
button.setTitleColor(.blue, for: .normal)
button.setTitleColor(.red, for: .highlighted)
button.titleLabel?.numberOfLines = 1
button.tag = 1
button.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
#objc func buttonPressed(_ sender: UIButton) {
// MARK: - Clear Filters button pressed:
if sender.tag == 1 {
}
}
Why don't you try implementing that inside the buttonPressed function?
#objc func buttonPressed(_ sender: UIButton) {
sender.setTitleColor(color: UIColorUI, for: UIControl.State)
}
This issue is that you are using setTitleColor for .normal and .highlighted states.
.normal is when the button is not clicked.
.highlighted is while the button is being clicked on.
Instead you could:
Just updated the .normal color when pressed (in buttonPressed); or
setTitleColor for .selected for after it's clicked and handle the selection state within buttonPressed (add sender.isSelected = !sender.IsSelected)
I have a view in my tabbar controller where I would like to show a button. I create this button programmatically based of a condition, therefore I use the following code but nothing is appearing:
override func viewDidLoad() {
super.viewDidLoad()
if !Settings.getIsConnected() {
notConnected()
}
}
func notConnected() {
let connectBtn = UIButton(frame: CGRect(x: self.view.center.x, y: self.view.center.y, width: 200, height: 45))
connectBtn.setTitle("Connect", forState: .Normal)
connectBtn.addTarget(self, action:#selector(self.pressedConnect(_:)), forControlEvents: .TouchUpInside)
self.view.addSubview(connectBtn)
print("Button created")
}
func pressedConnect(sender: UIButton!) {
}
I am clueless on what I am doing wrong. Anyone got suggestions? Cause it does print out "Button created" so it definitely runs the code inside the noConnected() method.
Add a background color to your UIButton and add a tint color to the title. This will resolve the problem
Try moving the code to viewDidAppear and see if the button is showing up.
The frame is not correctly set when in viewDidLoad. Use the method viewDidLayoutSubviews for the earliest possible time where the frame is correctly setup for a ViewController.
With this code change, you will need some additional logic for when your button should be added as a subview though.
A programmatically created button may not show up because of more reasons, e.g:
the tint color is not set
the background color is not set
the button is not added to the view hierarchy
the button is hidden
In your case, you should change the tint color or the background color of your button.
E.g.:
Swift 4.2:
private lazy var connectButton: UIButton = {
let button = UIButton(type: .custom)
button.backgroundColor = .green
button.setTitleColor(.black, for: .normal)
button.setTitle(NSLocalizedString("Connect", comment: ""), for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(connectButton)
}
You can re-check the button properties in the storyboard that it is not hidden.
I create a button from my code.
How can I write code to let button change to like Default?
Am I missing some code?
I have tried adjustsImageWhenHighlighted or something ....
I mean when I push Button ..the button will become to transparent(I still push on) and when i push off will become back ...
like down below two images...
import UIKit
class ViewController: UIViewController {
var testButton:UIButton = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = UIColor.whiteColor()
testButton.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
testButton.backgroundColor = UIColor.whiteColor()
testButton.setTitle("123", forState:.Normal)
testButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
testButton.tag = 1
testButton.addTarget(self, action: #selector(number), forControlEvents: .TouchUpInside)
self.view.addSubview(testButton)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func number(){
print("\("100")")
}
}
You could either add:
testButton.setTitleColor(UIColor.redColor(), forState: .Highlighted)
or have the colour applied in the button's function:
#IBAction func testButton(sender: UIButton) {
testButton.titleLabel.textColor = UIColor.redColor()
}
I've used redColor here for the examples, but you could change that to whatever colour you want to create the desired effect. I've not actually compiled this, so apologies if you need to correct any of the syntax to get it to work.
I'm trying to implement a simple UIButton (tvOS & Swift), but the TouchDown event isn't firing. (tried also TouchUpInside).
In the simulator I can see visually that the button is pressed.
my ViewController.swift code is:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(type: UIButtonType.System)
button.frame = CGRectMake(100, 100, 400, 150)
button.backgroundColor = UIColor.greenColor()
button.setTitle("Test", forState: UIControlState.Normal)
button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchDown)
self.view.addSubview(button)
self.view.userInteractionEnabled = true
}
func buttonAction(sender:UIButton!){
NSLog("Clicked")
}
}
What do I need to do in order to detect a button click?
You shouldn't be using ".TouchDown" or ".TouchUpInside" on tvOS, since that doesn't do what you might expect: you probably want to use "UIControlEvents.PrimaryActionTriggered" instead.
TouchUpInside is triggered by actual touches, which isn't really what happen. If you want the Select button press on the remote to trigger your button, you should use PrimaryActionTriggered.
UIControl.Event.primaryActionTriggered is required for tvOS addTarget method:
button.addTarget(self, action: #selector(ViewController.didTapAcctionButton(_:)), for: .primaryActionTriggered)
I've added some buttons in a Swift game for tvOS.
override func didMoveToView(view: SKView) {
let button1=UIButton(frame: CGRectMake(330, 800, 300, 100))
button1(imageBuySelected, forState: UIControlState.Focused)
button1(imageBuyNormal, forState: UIControlState.Normal
button1 = UIColor.clearColor()
button1(self, action: "buy1", forControlEvents: UIControlEvents.PrimaryActionTriggered)
self.view!.addSubview(button1)
let button2=UIButton(frame: CGRectMake(330, 800, 300, 100))
button2(imageBuySelected, forState: UIControlState.Focused)
button2(imageBuyNormal, forState: UIControlState.Normal
button2 = UIColor.clearColor()
button2(self, action: "buy2", forControlEvents: UIControlEvents.PrimaryActionTriggered)
self.view!.addSubview(button2)
let button3=UIButton(frame: CGRectMake(330, 800, 300, 100))
button3(imageBuySelected, forState: UIControlState.Focused)
button3(imageBuyNormal, forState: UIControlState.Normal
button3 = UIColor.clearColor()
button3(self, action: "playGame", forControlEvents: UIControlEvents.PrimaryActionTriggered)
self.view!.addSubview(button3)
}
When the games starts. The initial focus is set to button1. I want the focus to be set to button3. I understand that the preferred focus is automatically selected based on the first focusable object found starting from the upper left corner of the screen. Does anyone know how override this so I can make button3 the preferredfocusview when the game starts?
I hope this is what you were looking for, good luck! :)
override var preferredFocusedView: UIView? {
get {
return self.button3
}
}
In your view or view controller, override the preferredFocusedView method to return button3.
You can read more about this method under the Preferred Focus Chain section of the documentation.
preferredFocusedView is Depreciated, So use below
#IBOutlet weak var viewTemp: UIView!
override var preferredFocusEnvironments : [UIFocusEnvironment] {
//Condition
return [viewTemp]
}