I've been trying to get a sync button to display Last Sync at (time&date). But All I get is one line with shortened text.
// Sync Button
syncBtn.frame = CGRectMake(15, height-60, 120, 40)
syncBtn.addTarget(self, action: "syncBtnPressed", forControlEvents: UIControlEvents.TouchUpInside)
syncBtn.setTitle("Last Sync: Never", forState: UIControlState.Normal)
syncBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
syncBtn.layer.borderColor = UIColor.whiteColor().CGColor
syncBtn.layer.borderWidth = 1
syncBtn.layer.cornerRadius = 5
syncBtn.titleLabel?.font = UIFont(name: "Avenir", size: 10)
syncBtn.alpha = 0.5
syncBtn.titleLabel?.sizeToFit()
syncBtn.titleLabel?.textAlignment = NSTextAlignment.Center
syncBtn.titleLabel?.numberOfLines = 2
self.view.addSubview(syncBtn)
This is the function to get and set the date on the label
func printTimestamp(){
var timestamp = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .ShortStyle, timeStyle: .ShortStyle)
self.syncBtn.titleLabel?.text = ("Last Sync at: " + timestamp)
}
Anyone able to solve this problem?
create a UIButton with Multiple lines of text
Possible programtically
override func viewDidAppear(animated: Bool){
super.viewDidAppear(animated)
btnTwoLine.setTitle("Mulitple line", forState: UIControlState.Normal)
btnTwoLine.titleLabel!.lineBreakMode = NSLineBreakMode.ByWordWrapping;
}
Use SetTitle method instead of .text , when you use .text it sets the title text but the constraints are not updated accordingly hence you need to use SetTitle method and set the adjustsFontSizeToFitWidth to true
self.syncBtn.setTitle(timeStamp, forState: UIControlState.Normal)
self.syncBtn.titleLabel?.adjustsFontSizeToFitWidth = true
Related
I want to set my Switch like this:
But I try in ios9 , it does not work.
I saw in apple UISwitch Class Reference.
It says that :
Discussion
In iOS 7, this property has no effect.
How about iOS 9? Any one success?
My Code:
switch1 = UISwitch(frame:CGRectMake(self.view.frame.width/2 - 20, 400, 10, 100))
switch1.on = true
switch1.onTintColor = UIColor.lightGrayColor()
switch1.tintColor = UIColor.greenColor()
switch1.thumbTintColor = UIColor.blackColor()
//set on/off image
switch1.onImage = UIImage(named: "on-switch")
switch1.offImage = UIImage(named: "off-switch")
Use a UIButton instead.
let switchButton = UIButton(type: .Custom)
switchButton.selected = true
switchButton.setImage(UIImage(named: "on-switch"), forState: .Selected)
switchButton.setImage(UIImage(named: "off-switch"), forState: .Normal)
Use switchButton.isSelected instead of switch1.on. You'll have to toggle switchButton.isSelected when it is tapped, which you can do like this:
switchButton.isSelected.toggle()
For iOS 13, you could do this way:
let switcher = UISwitch()
switcher.addTarget(self, action: #selector(pressed), for: .valueChanged)
#objc func pressed(sender: UISwitch) {
let color = UIColor(patternImage: UIImage(named: sender.isOn ? "on.png": "off.png")!)
if sender.isOn {
sender.onTintColor = color
} else {
sender.tintColor = color
sender.subviews[0].subviews[0].backgroundColor = color
}
}
NOTE: your image should look like:
Then the final result is:
Not an exact answer to your question, but if you want a completely custom button switch programmatically (that you can add text to), this will work too:
import UIKit
class RDHiddenVisibleButton: UIButton {
// Hidden / Visible Button Function
var isOn = false
override init(frame: CGRect) {
super.init(frame: frame)
initButton()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initButton()
}
func initButton() {
layer.borderWidth = 2.0
layer.borderColor = Colors.radiusGreen.cgColor
layer.cornerRadius = frame.size.height/2
setTitleColor(Colors.radiusGreen, for: .normal)
addTarget(self, action: #selector(RDHiddenVisibleButton.buttonPressed), for: .touchUpInside)
}
#objc func buttonPressed() {
activateButton(bool: !isOn)
}
func activateButton(bool: Bool) {
isOn = bool
let color = bool ? Colors.radiusGreen : .clear
let title = bool ? "Hidden" : "Visible"
let titleColor = bool ? . white : Colors.radiusGreen
setTitle(title, for: .normal)
setTitleColor(titleColor, for: .normal)
backgroundColor = color
}
}
When I press the play again button it doesn't work. I just have this code involving the play again button. What should I add here? How can I add a function to playAgain button? Here is my code:
let playAgain: UIButton = UIButton(frame: CGRectMake(-10, 400, 400, 150))
playAgain.setTitle("Play Again", forState: UIControlState.Normal)
playAgain.titleLabel!.font = UIFont(name: "Helvetica", size: 50)
playAgain.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
playAgain.tag = 1
self.view!.addSubview(playAgain)
Implement a function with any name you like, like this:
func buttonPressed(sender: UIButton) {
// do something
}
Then set this function as the action of your button:
playAgain.addTarget(self, action: "buttonPressed:", forControlEvents: .TouchUpInside)
i have an UIImagePickerController and 2 buttons. When I tap on button 1 I want to set the image of button 1. And when I tap on button 2 I want to set the image of button 2. I've successfully set the image of button 1 using UIImagePickerController but failed to do so with button 2. Here's my code:
var whichButton: Int = 0
func displayImagePicker(){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
imagePicker.allowsEditing = false
self.presentViewController(imagePicker, animated: true, completion: nil)
}
#IBAction func chooseImageOne(sender: AnyObject) {
displayImagePicker()
whichButton = 1
}
#IBAction func chooseImageTwo(sender: AnyObject) {
displayImagePicker()
whichButton = 2
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
self.dismissViewControllerAnimated(true, completion: nil)
if whichButton == 1 {
self.imageOne.setImage(image, forState: UIControlState.Normal)
} else if whichButton == 2 {
self.imageTwo.setImage(image, forState: UIControlState.Normal)
}
}
As you can see I tried having a var to keep track of which button I'm tapping on. I'm not sure what I've done in the didFinishPickingImage func is right. I'm very new to swift, if anyone can shed some light it will really be great! thanks in advance
I have personally checked your code on xcode and its correct. Please see if you have given IBOutlet to self.imageTwo button and also check for the IBAction i.e touchupInside for the imageTwo button. else everything is fine
Your code is functionally correct. Looks like your #IBAction functions are not hooked up correctly, or the #IBOutlet of the second button. You could easily check this with print statements in the button handlers, or in the debugger.
So I created my first label without story board today and I am wondering how to change the text of the label when I click a button. The action for the button works just fine. I did create an outlet for the label so I could refer to it out of the method I initially called it in but when I click the button the app crashes.
Here is my code:
import UIKit
import Foundation
class ThirdViewController: UIViewController {
#IBOutlet weak var label1: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.view.addBackground()
//label one
var label1 = UILabel(frame: CGRectMake(0, 0, view.bounds.width - 80, 30))
label1.center = CGPointMake(view.bounds.width/2, 20)
label1.textAlignment = NSTextAlignment.Center
label1.text = "Pick the largest number"
label1.font = UIFont(name: font, size: 25)
self.view.addSubview(label1)
//number one
var num1 = UIButton(frame: CGRectMake(0, 0, 100, 100))
num1.center = CGPointMake(view.bounds.width/4, view.bounds.height/4)
num1.setTitle("37", forState: UIControlState.Normal)
num1.addTarget(self, action: "num1Tapped", forControlEvents: UIControlEvents.TouchUpInside)
num1.titleLabel!.font = UIFont(name: font, size: 70)
self.view.addSubview(num1)
}
func num1Tapped(UIButton!){
label1.text = "test"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
There are a few problems with your code.
The property you define on top of class definition #IBOutlet weak var label1: UILabel! is not the same you define in (inside) the method viewDidLoad().
Here, you are creating a new local variable, with the same name of your property, an instance variable!
And this variable you created is only accessible inside the method, that's the scope for which it is defined.
The method num1Tapped(_:) is, as it has already been said here, incorrectly defined.
The action that is triggered by an UIControl can have three different signatures:
action()
action(_:)
action(_: forEvent:)
If you don't need a reference of the button and/or the event that triggered the action, you can just use the first one.
As it is now, and forgetting the wrong definition, when the method num1Tapped(_:) is called, it will try to access the instance variable label1, not the local variable defined in the method viewDidLoad(), which, by the way, is impossible to do it.
So, the next thing to resolve is this instance variable label1.
As you have defined, you must connect this declaration with an Outlet in the storyboard, or you must manually initialize the variable.
This is the code from your example that I used (with some modifications) to change the label when the button is touched, and assuming you are creating the label with code:
class ThirdViewController: UIViewController {
var label1: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//label one
label1 = UILabel(frame: CGRectMake(0, 0, view.bounds.width - 80, 30))
label1.center = CGPointMake(view.bounds.width/2, 20)
label1.textAlignment = NSTextAlignment.Center
label1.text = "Pick the largest number"
// label1.font = UIFont(name: font, size: 25)
view.addSubview(label1)
//number one
// let num1 = UIButton(frame: CGRectMake(0, 0, 100, 100))
let num1 = UIButton(type: .System)
num1.frame = CGRectMake(0, 0, 100, 100)
print("num1: \(num1)")
num1.center = CGPointMake(self.view.bounds.width/4, self.view.bounds.height/4)
num1.setTitle("37", forState: UIControlState.Normal)
num1.addTarget(self, action: "num1Tapped", forControlEvents: UIControlEvents.TouchUpInside)
// num1.addTarget(self, action: "num1TappedWithParameter:", forControlEvents: UIControlEvents.TouchUpInside)
// num1.addTarget(self, action: "num1TappedWithTwoParameters:event:", forControlEvents: UIControlEvents.TouchUpInside)
// num1.titleLabel!.font = UIFont(name: font, size: 70)
self.view.addSubview(num1)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func num1Tapped() {
label1.text = "test"
}
func num1TappedWithParameter(sender: UIButton){
label1.text = "test"
}
func num1TappedWithTwoParameters(sender: UIButton, event: UIEvent) {
print("button: \(sender.description) event: \(event)")
}
}
A few extra notes.
With the code you present I don't understand how it even compiles with the wrong signature of the method num1Tapped(UIButton!). This doesn't compile!
Did you change it (with the Xcode suggestion) to num1Tapped(_ :UIButton!)?
If you did, the app crashes because it can find the method you are calling since you defined as it having no parameters:
num1.addTarget(self, action: "num1Tapped", forControlEvents: UIControlEvents.TouchUpInside)
Another thing I don't understand is how can your button being displayed because you it's no set its type.
Did you define the button num1in storyboard and you (wrongly) tried to access here in the code?
addBackground()is commented since it's not here defined.
The same happens when setting the font.
I add two more methods so you can see how to use them.
Be consistent when writing your code. If you access the variable view without the self, do the same when adding the subviews: view.addSubview(num1), or of course, the opposite, use self in both situations.
I hope this helps with your problem.
Your code is almost correct except of a few small changes:
override func viewDidLoad() {
super.viewDidLoad()
self.view.addBackground()
//label one
var label1 = UILabel(frame: CGRectMake(0, 0, view.bounds.width - 80, 30))
label1.center = CGPointMake(view.bounds.width/2, 20)
label1.textAlignment = NSTextAlignment.Center
label1.text = "Pick the largest number"
label1.font = UIFont(name: font, size: 25)
self.view.addSubview(label1)
//number one
var num1 = UIButton(frame: CGRectMake(0, 0, 100, 100))
num1.center = CGPointMake(view.bounds.width/4, view.bounds.height/4)
num1.setTitle("37", forState: UIControlState.Normal)
num1.addTarget(self, action: "num1Tapped:", forControlEvents: UIControlEvents.TouchUpInside)
num1.titleLabel!.font = UIFont(name: font, size: 70)
self.view.addSubview(num1)
}
func num1Tapped(sender: UIButton!){
label1.text = "test"
}
#user2893289 was correct and so was #Arc676. You need to add the ":" in the action and add sender: UIButton! as the buttons action.
I have this code that shares a screenshot of the app, an initial Text and a URL via the Apple Share menu when a Share Button is pressed. It works like a charm with Twitter, Messages, Email etc, but when i wanna share to Facebook or the Facebook Messenger, the text doesn't show up (but the image and the URL do).
Any idea why that is and how to fix it?
I was able to share text and a URL to Facebook with other functions (but they didn't deliver the right screenshot so i switched to this one).
Thanks in advance!
Edit: The text does get shared in the xcode Simulator, just not on the iPhone(s).
func takeSnapshot(view: UIView) {
let bounds = UIScreen.mainScreen().bounds
UIGraphicsBeginImageContextWithOptions(bounds.size, true, 0.0)
self.view.drawViewHierarchyInRect(bounds, afterScreenUpdates: false)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let text = "Text to be shared... #Hashtag"
let URL = NSURL(string: "http://stackoverflow.com/")!
let activityViewController = UIActivityViewController(activityItems: [image, text, URL], applicationActivities: nil)
self.presentViewController(activityViewController, animated: true, completion: nil)
}
An update to the Facebook application has replaced the in-built Facebook share activity with one that ignores status text - If you remove the Facebook app from your device the text will be displayed using the code you have. If you have the Facebook app installed you get images, URLs but not the text.
Follow the instructions: https://developers.facebook.com/docs/sharing/ios
Then you can do something like this:
Share a link
let content : FBSDKShareLinkContent = FBSDKShareLinkContent()
content.contentURL = NSURL(string: "<INSERT STRING HERE>")
content.contentTitle = "<INSERT STRING HERE>"
content.contentDescription = "<INSERT STRING HERE>"
content.imageURL = NSURL(string: "<INSERT STRING HERE>")
let button : FBSDKShareButton = FBSDKShareButton()
button.shareContent = content
button.frame = CGRectMake((UIScreen.mainScreen().bounds.width - 100) * 0.5, 50, 100, 25)
self.view.addSubview(button)
Share Photos
class ViewController: UIViewController, FBSDKLoginButtonDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate
let button : UIButton = UIButton()
button.backgroundColor = UIColor.blueColor()
button.setTitle("Choose Photo", forState: .Normal)
button.frame = CGRectMake((UIScreen.mainScreen().bounds.width - 150) * 0.5, 125, 150, 25)
button.addTarget(self, action: "photoBtnClicked", forControlEvents: .TouchUpInside)
self.view.addSubview(button)
let label : UILabel = UILabel()
label.frame = CGRectMake((UIScreen.mainScreen().bounds.width - 200) * 0.5, 100, 200, 25)
label.text = "Photos Example"
label.textAlignment = .Center
self.view.addSubview(label)
func photoBtnClicked(){
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.SavedPhotosAlbum){
println("Photo capture")
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum;
imagePicker.allowsEditing = false
self.presentViewController(imagePicker, animated: true, completion: nil)
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
let photo : FBSDKSharePhoto = FBSDKSharePhoto()
photo.image = info[UIImagePickerControllerOriginalImage] as! UIImage
photo.userGenerated = true
let content : FBSDKSharePhotoContent = FBSDKSharePhotoContent()
content.photos = [photo]
}
Photos must be less than 12 MB in size
Share Video on Facebook
class ViewController: UIViewController, FBSDKLoginButtonDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate
let button : UIButton = UIButton()
button.backgroundColor = UIColor.blueColor()
button.setTitle("Choose Video", forState: .Normal)
button.frame = CGRectMake((UIScreen.mainScreen().bounds.width - 150) * 0.5, 200, 150, 25)
button.addTarget(self, action: "videoBtnClicked", forControlEvents: .TouchUpInside)
self.view.addSubview(button)
let label : UILabel = UILabel()
label.frame = CGRectMake((UIScreen.mainScreen().bounds.width - 200) * 0.5, 175, 200, 25)
label.text = "Video Example"
label.textAlignment = .Center
self.view.addSubview(label)
func videoBtnClicked(){
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSource Type.SavedPhotosAlbum){
println("Video capture")
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum
imagePicker.allowsEditing = false
self.presentViewController(imagePicker, animated: true, completion: nil)
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
let video : FBSDKShareVideo = FBSDKShareVideo()
video.videoURL = info[UIImagePickerControllerMediaURL] as! NSURL
let content : FBSDKShareVideoContent = FBSDKShareVideoContent()
content.video = video
}
Videos must be less than 12MB in size. I hope I have helped you. (Sorry for my english)