Simple tvOS UIButton is not working - swift

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)

Related

Swift UIButton titleColor change when highlighted?

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)

Swift dynamic button create

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

Swift UIButton not appearing on screen

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.

How do I set the initial focus on buttons in a view controller running on tvOS (AppleTV)?

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

UIButton created programmatically. How do I send touch up's to an IBAction?

I have a UIButton which is created programmatically. How do I get this UIButton to send its touch up events to an IBAction I have?
addTarget:action:forControlEvents: method.
[myButton addTarget:myClass action:#selector(myEventHandler) forControlEvents: UIControlEventTouchUpInside];
From http://developer.apple.com/library/ios/#documentation/uikit/reference/UIControl_Class/Reference/Reference.html.
with this line of code you will fire UIbutton action by programmatically
[button sendActionsForControlEvents:UIControlEventTouchUpInside];
For swift
button.addTarget(self, action:#selector(functionNameHere), for: UIControl.Event.touchUpInside)
[button addTarget:self
action:#selector(myMethod:)
forControlEvents:UIControlEventTouchUpInside];
Like magic =)
Swift 3.0
button.addTarget(self, action:#selector(funcName), for: UIControlEvents.touchUpInside)
Swift 5
You can also send the sender to identify the touched button. Plus, don't forget to add objc before your function name:
private func setOnClicks() {
btn.addTarget(self, action: #selector(onBtnClick), for: .touchUpInside)
}
#objc func onBtnClick(_ sender: UIButton) -> Void {
print("touched \(sender.tag)")
}
Easily set add action for UIButton using addTarget(,action:,for:)
let addVehicleButton = UIButton() // Create a button
addVehicleButton.setTitle("Add vehicle", forState: .normal) // set title
addVehicleButton.frame = CGRectMake(20, 50, 50, 40) // setting frame
addVehicleButton.addTarget(self, action: #selector(addVehicleButtonClickedAction), for: .touchUpInside) // Add target and control event with trigger function selector
self.view.addSubview(addVehicleButton) // adding to superview
// MARK: - Click action handles
/// Add vehicle button clicked action
#objc func addVehicleButtonClickedAction() {
}