I am creating a post to twitter app and want to add various text to the UITextField from buttons that can be selected. The UIButton are for various hashtags to speed the process of writing a tweet. I have tried a couple the solutions found on Stack but none seem to work and they are all in Objective-C.
Screenshot of compose tweet view before buttons touched.
http://postimg.org/image/5qoyk6673/
Screenshot of compose tweet view after button selected and text added to text field.
http://postimg.org/image/vp08wsa6b/fa7c7a83/
class TweetComposeViewControler: UIViewController, UITextViewDelegate {
var selectedAccount : ACAccount!
#IBOutlet var tweetContent: UITextView!
#IBAction func specializedButton(sender: UIButton) {
tweetContent.text = sender as UIButton
tweetContent.text.stringByAppendingString(specializedButton(titleLabel.text))
}
func insertHashtag(sender: UIButton!) {
tweetContent.text = tweetContent.text.stringByAppendingString(sender.titleLabel.text)
}
You can set the UITextFields text to the title of your UIButton:
txtField.text = hashTagButton.titleLabel.text
And if you want to append the text:
txtField.text = textField.text.stringByAppendingString(hashTagButton.titleLabel.text)
In order to have your buttons update the text upon pressing them you need to add a target selector for when the buttons are pressed. This can be done via Storyboard or programmatically.
Programmatically
You would add the same selector to all buttons using this:
hashtagButton.addTarget(self, action: Selector("insertHashtag:"), forControlEvents: .TouchUpInside)
This will call the insertHashtag function whenever the hashtagButton is pressed. Because of the : at the end of the selector, it will also pass itself as a parameter so you can use it to get the button's title rather than creating a different selector for each button.
func insertHashtag(sender: UIButton!) {
txtField.text = textField.text.stringByAppendingString(sender.titleLabel!.text)
}
Using IBAction
#IBAction func insertHashtag(sender: AnyObject) {
txtField.text = sender as UIButton
textField.text.stringByAppendingString(btn.titleLabel!.text)
}
Here you cast the sender paramter as a UIButton since you know a UIButton is the type of the object which called it.
If you know that only UIButton's will cause this method you can do this:
#IBAction func insertHashtag(btn: UIButton ) {
txtField.text = sender as UIButton
textField.text.stringByAppendingString(btn.titleLabel!.text)
}
Response to your update
The code you added needs to be fixed to look like this:
#IBAction func specializedButton(sender: UIButton) {
tweetContent.text.stringByAppendingString(sender.titleLabel!.text)
}
Here sender is your UIButton and you pass it as a UIButton so you do not need to convert it.
Related
I have an empty array, and I have #IBAction func test(_ sender: UIButton) with 25 different buttons attached to this func. how can I write the code for appending a button title to the array, when pressed?
someArray.append = (this part that I can't figure out?)
Since I don't know which button/buttons will be pressed I can't just write someArray.append = ("buttonTitle")
(ive googled and searched in here for hours, but I can't find the solution)
if let title = sender.title(for: sender.state) {
someArray.append(title)
}
For multiple UIButtons with single IBOutlet Action you can add tags for each UIButton.
So if you've used StoryBoard for UIButtons, so when you click on single UIButton - navigate to Attribute Inspector & add tag to each button. As shown in below fig.1.0
I've set all UIButtons with different title & tags.
Once you set tags, for all buttons, then programmatically you can identify which button is clicked via single - onClick function.
#IBAction func Click(_ sender: UIButton) {
if let title = sender.title(for: sender.state){
print(title)
//Here we are identifying which button is pressed. If I pressed UIButton.tag = 1 then I'm just printing it's title, else appending UIButton value in array.
if sender.tag == 1 {
print(sender.title(for: sender.state))
}
else{
self.someArray.append(title)
}
}
}
So, in this way you can identify all your UIButton actions within a single event action.
#IBOutlet weak var btnoutlet: UIButton!
if let title = btnoutlet.currentTitle {
someArray.append(title)
}
We want Lyft button touch event because I am working in analytics, so, I need how many people choose Lyft but I can't put UIView click event. I try below code.
let gesture = UITapGestureRecognizer(target: self, action: #selector(self.checkAction))
cell.lyftButton.addGestureRecognizer(gesture)
How can i achieve this?
You can directly assign a selector method to lyftButton e.g
lyftButton.addTarget(self, action: #selector(lyftButtonAction(_:)), for: .touchUpInside)
#objc
func lyftButtonAction(_sender: UIButton) {
//Do your action
}
To retrieve the LyftButton, you'll need to fetch the button inside the Lyft view, after retrieving it, I tried to add another target to it which was your 'checkAction' method, but for some reason it is not being called. One workaround solution is:
On Auto Layout, created a transparent button on top of the Lyft Button View, let's callet it 'Transparent Lyft Button': Example (I've embeded in another view because it was on a stackView);
On the code, retrieved the button with the above method, held it in a variable, let's call it 'requestLyftButton' and disabled it.
Created an IBAction for the 'Transparent Lyft Button' that triggers the method 'self.checkAction' that you've created and also calls requestLyftButton.sendActions(for: .touchUpInside), which triggers the original Lyft SDK action.
To Retrieve Lyft UIButton:
#IBOutlet weak var lyftButton: LyftButton!
#IBOutlet weak var transparentLyftButton: UIButton!
var requestLyftButton: UIButton?
func retrieveLyftButton(in view: UIView) {
for view in view.subviews {
if let lyftBtn = view as? UIButton {
lyftBtn.isEnabled = false
requestLyftButton = lyftBtn
} else {
retrieveLyftBtn(in: view)
}
}
}
transparentLyftButton IBAction to trigger your method + lyft sdk original action:
#IBAction func requestLyft(_ sender: UIButton) {
if let lyftBtn = requestLyftButton {
checkAction() // Your method
lyftBtn.sendActions(for: .touchUpInside)
}
}
I hope that you can understand what was done, if you have any questions, just let me know.
I have created a custom view that is to be used as a radio button with images and text. I need to be able to load the saved selection when the controller loads. I set my listeners this way:
for button in genderButtons {
button.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(genderTapped(_:))))
}
#objc private func genderTapped(_ sender: UITapGestureRecognizer) {
for button in genderButtons {
button.select(sender.view! == button) // Toggles the button to display selected/deslected state.
...
}
}
The problem is that I can't find a way to tell the view to select. I tried making the gesture recognizer and object, but it doesn't have any methods I can use to trigger it. The 'buttons' aren't actually buttons, they're views, so I can't send an action event.
How can I select the correct button with code?
Just call genderTapped directly, handing it the gesture recognizer already attached to the desired "button".
For example, if thisGenderButton is the one you want to "tap", say:
if let tap = thisGenderButton.gestureRecognizers?[0] as? UITapGestureRecognizer {
genderTapped(tap)
}
You can add this method in your customView like this,
Class CustomView: UIView {
public func select(_ value: Bool) {
self.backgroundColor = value ? .green: .red
}
}
and then in below method you can call select for the tapped view.
#objc private func genderTapped(_ sender: UITapGestureRecognizer) {
(sender.view as? CustomView)?.select(true)
}
This is a very basic question but I'm not sure what the problem is. I'm trying to make a simple "hello world" program where the user inputs what they want into the textfield and whatever they enter goes into the label. However, nothing seems to be happening and I'm unsure why since my push function worked exactly how I expected it to.
import UIKit
class ViewController: UIViewController {
#IBOutlet var PopUp: UITextField!
#IBOutlet weak var HelloWorld: UILabel!
#IBAction func Push(_ sender: UIButton) {
PopUp.isHidden = false
PopUp.text = "hello World"
}
#IBAction func send(_ sender: UITextField) {
HelloWorld.text = sender.text
}
}
Based on the code you provided, func send is an unknown to me, as to whether or not it is even firing. func send might be called, might not, either way, it is strange to see a _ sender: UITextField for an IBAction.
What event are you firing related to the UITextField? Are you trying to update your HelloWorld UILabel as the user types in the UITextfield?
To update your UILabel with whatever has been typed in your UITextField, you just need a UIButton Touch Up Inside IBAction. I think you can delete IBAction func send completely, unless you are trying to update the UILabel as the user types in the UITextField. Make sure you remove the IBAction Outlet from your Storyboard if I am correct about this point.
Based on the code you provided the Push func does not set text in your UILabel. I am assuming Push is an UIButton Touch Up Inside IBAction. You can set your HelloWorld UILabel text, in func Push, you do not need to use the sender of the event, try this and you will see the HelloWorld UILabel text populated:
#IBAction func Push(_ sender: UIButton) {
//PopUp.isHidden = false //why are you doing this? the UITextField PopUp should already be visible if you are typing text into it, so this code is superfluous as the value of PopUp.isHidden is already false
HelloWorld.text = PopUp.text
PopUp.text = "hello World"
}
If you are trying to have your UILabel display the text as you type into the UITextField you should clarify your question. And if it is the case you will need to make your UIViewController a UITextFieldDelegate
Here is the one way of approach :
override func viewDidLoad() {
super.viewDidLoad()
PopUp.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged) // when textfield is edited this will call
}
func textFieldDidChange(_ textField: UITextField) {
HelloWorld.text = textField.text
}
I'm new to Swift and I assume this is a fundamental question to programming for iOS.
I have three buttons in my storyboard and I want to customize how those buttons look if pressed once, twice and three times.
I also have three themes (pink, blue and orange). What I thought of doing is to create three new classes called pink,blue and orange.swift
I don't want to create them programmatically, only style them programmatically.
What I lack to understand is how do I call the function (Example: "ButtonIsPressed") from my pink.swift class into my #IBAction and #IBOutlet in the main view controller that is also object oriented (ie. I don't want to create a function for every button)?
I can't really find a decent and up-to-date Swift 3 Tutorial for this, any help or advice on this topic will be greatly appreciated.
Why can it not be as simple as?:
#IBAction func buttonPressed(_ sender: UIButton!) {
self.backgroundColor = myPinkCGolor
}
I think shallowThought's answer will work for changing backgroundColor based on button state of a specifically named IBOutlet.
I have three buttons in my storyboard and I want to customize how those buttons look if pressed once, twice and three times.
If you want to maintain "state", as in have a "counter" for how many times a button's been clicked or tapped, you can use the "tag" property of the button. Set it to zero, and in your IBAction functions increment it. (Like shallowThought said, use .touchUpInside and .touchDown for the events.)
Also, you have one minor - but important! - thing wrong in your code Brewski:
#IBAction func buttonPressed(_ sender: UIButton!) {
self.backgroundColor = myPinkCGolor
}
Should be:
#IBAction func buttonPressed(_ sender: UIButton!) {
sender.backgroundColor = myPinkCGolor
}
So combining everything - up vote to shallowThought (also, changing his AnyObject to UIButton and making it Swift 3.x syntax on the UIColors - and would end up with this. Note that there is no need for an IBOutlet, and you can wire everything up in IB without subclassing:
// .touchUpInside event
// can be adapted to show different color if you want, but is coded to always show white color
#IBAction func buttonClicked(sender: UIButton) {
sender.backgroundColor = UIColor.whiteColor()
}
// .touchDown event
// will show a different color based on tap counter
#IBAction func buttonReleased(sender: UIButton) {
switch sender.tag {
case 1:
sender.backgroundColor = UIColor.blue
case 2:
sender.backgroundColor = UIColor.red
case 3:
sender.backgroundColor = UIColor.green
default:
sender.backgroundColor = UIColor.yellow
}
sender.tag += 1
}
There is no methode to set the backgroundColor for a certain state, like there is for other UIButton properties, so you have to listen to the buttons actions:
class ViewController: UIViewController {
#IBOutlet weak var button: UIButton!
#IBAction func buttonClicked(sender: AnyObject) { //Touch Up Inside action
button.backgroundColor = UIColor.whiteColor()
}
#IBAction func buttonReleased(sender: AnyObject) { //Touch Down action
button.backgroundColor = UIColor.blueColor()
}
...
}
or set a unicolor image withimage:UIImage, forState:.selected.