NSTextlist issue in Swift - macos

I wrote the following code to get list in a nstextview. The issue is, in first line number (1) is appearing correctly and after entering some data and press enter second line number (2) should automatically appear. but it isn't. Any help is appreciated
#IBAction func numberList(sender: AnyObject) {
self.editorView.textStorage?.beginEditing()
var paragraph : NSMutableParagraphStyle = NSMutableParagraphStyle()
var textList : NSTextList = NSTextList(markerFormat: "{decimal}.", options: 0)
paragraph.textLists = [textList]
var attributedString : NSAttributedString = NSAttributedString(string: "\t \(textList.markerForItemNumber(1)) \t", attributes: [paragraph : NSParagraphStyleAttributeName])
self.editorView.textStorage?.appendAttributedString(attributedString)
self.editorView.textStorage?.endEditing()
}

Related

How can I find the substrings from the NSTextCheckingResult objects in swift?

I wonder how it is possible to find substrings from a NSTextCheckingResult object. I have tried this so far:
import Foundation {
let input = "My name Swift is Taylor Swift "
let regex = try NSRegularExpression(pattern: "Swift|Taylor", options:NSRegularExpressionOptions.CaseInsensitive)
let matches = regex.matchesInString(input, options: [], range: NSMakeRange(0, input.characters.count))
for match in matches {
// what will be the code here?
}
Try this:
import Foundation
let input = "My name Swift is Taylor Swift "// the input string where we will find for the pattern
let nsString = input as NSString
let regex = try NSRegularExpression(pattern: "Swift|Taylor", options: NSRegularExpressionOptions.CaseInsensitive)
//matches will store the all range objects in form of NSTextCheckingResult
let matches = regex.matchesInString(input, options: [], range: NSMakeRange(0, input.characters.count)) as Array<NSTextCheckingResult>
for match in matches {
// what will be the code
let range = match.range
let matchString = nsString.substringWithRange(match.range) as String
print("match is \(range) \(matchString)")
}
Here is code that works for Swift 3. It returns array of String
results.map {
String(text[Range($0.range, in: text)!])
}
So overall example could be like this:
let regex = try NSRegularExpression(pattern: regex)
let results = regex.matches(in: text,
range: NSRange(text.startIndex..., in: text))
return results.map {
String(text[Range($0.range, in: text)!])
}
You can put this code inside the for loop. The str will contain the string that matches.
let range = match.range
let str = (input as NSString).substringWithRange(range)

Xcode Air print

I am a beginner with xcode and swift.
I have a couple of fields and a image in my viewcontroller and I would like to print the content of this fields...
My code from a tutorial:
#IBAction func print(sender: AnyObject) {
// 1
let printController = UIPrintInteractionController.sharedPrintController()
// 2
let printInfo = UIPrintInfo(dictionary:nil)
printInfo.outputType = UIPrintInfoOutputType.General
printInfo.jobName = "Rapport"
printController.printInfo = printInfo
// 3
let formatter = UIMarkupTextPrintFormatter(markupText: itemName.text!)
formatter.contentInsets = UIEdgeInsets(top: 72, left: 72, bottom: 72, right: 72)
printController.printFormatter = formatter
// 4
printController.presentAnimated(true, completionHandler: nil)
}
works very well with this only textfield. But how can I print the rest of it?
You are using a formatter to send to the printController and send him a markup text to print. This function takes a string, so you can create a custom string with all the text you want it to have and call the function, like this:
// 3
let myMarkupText = itemName.text! + "\n" + secondField.text! + "\n" + anotherField.text!
let formatter = UIMarkupTextPrintFormatter(markupText: myMarkupText)
...
I added the "\n" to start a new line, but you can format it the way you want, of course. I'm not sure if "\n" would create a new line anyway (since this is markup, maybe you need <br />), you'd have to try and see.
If you wanted to print the whole page instead of just certain parts, you could also check the documentation for UIPrintInteractionController to see what other options you have (printingItem, printingItems, printPageRenderer).
Alternatively, if you have a long string with multiple \n carriage returns, you need to first replace all of the \n occurrences with br / before submitting the string to the UIMarkupTextPrintFormatter. Here is an example for Swift 4:
func print(text: String) {
let textWithNewCarriageReturns = text.replacingOccurrences(of: "\n", with: "<br />")
let printController = UIPrintInteractionController.shared
let printInfo = UIPrintInfo(dictionary: nil)
printInfo.outputType = UIPrintInfoOutputType.general
printController.printInfo = printInfo
let format = UIMarkupTextPrintFormatter(markupText: textWithNewCarriageReturns)
format.perPageContentInsets.top = 72
format.perPageContentInsets.bottom = 72
format.perPageContentInsets.left = 72
format.perPageContentInsets.right = 72
printController.printFormatter = format
printController.present(animated: true, completionHandler: nil)
}

Check Mac battery percentage in swift

I have been trying to check the mac battery level programmatically.it can be done on ios but i want to do it in mac.i found some resources on stackoverflow but those links were deprecated. Any Ideas?
First create a "Umbrella-Bridging-Header.h"
with the content:
#import <IOKit/ps/IOPowerSources.h>
then in main.swift
import Foundation
println("Hello, World!")
let timeRemaining = IOPSGetTimeRemainingEstimate ()
println("timeRemaining: \(timeRemaining)")
If you don't want to add Objective-C bridging and you need just to know a couple of values. Then you could use this function.
func getBatteryState() -> [String?]
{
let task = Process()
let pipe = Pipe()
task.launchPath = "/usr/bin/pmset"
task.arguments = ["-g", "batt"]
task.standardOutput = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as! String
let batteryArray = output.components(separatedBy: ";")
let source = output.components(separatedBy: "'")[1]
let state = batteryArray[1].trimmingCharacters(in: NSCharacterSet.whitespaces).capitalized
let percent = String.init(batteryArray[0].components(separatedBy: ")")[1].trimmingCharacters(in: NSCharacterSet.whitespaces).characters.dropLast())
var remaining = String.init(batteryArray[2].characters.dropFirst().split(separator: " ")[0])
if(remaining == "(no"){
remaining = "Calculating"
}
return [source, state, percent, remaining]
}
print(getBatteryState().flatMap{$0}) -> "AC Power", "Discharging", "94", "3:15"
pmset is a very old command line function which is very unlikely to change in the future. Of course this does not give extended properties of power options like mAh and so on, but it was enough for me, because I just needed to know is it charging or not and how much percent battery has currently.
Just my 2 cents. I understand if people will find this discouraging to use.
N.B. If charging - remaining will show how long until it's fully charged.
If discharging - it will show how long until it's discharged.
First, you can see the answer here on how to include Objective-C code in your swift project (very good post btw).
Then, check out the IOMPowerSource class. It should include everything you need to report the status of the computer's power information.
Swift 2 Version of the answer of #Just A Minnion
import Cocoa
class ViewController: NSViewController {
#IBOutlet weak var label: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
label.stringValue = String(getBatteryState().flatMap{$0})
}
func getBatteryState() -> [String?] {
let task = NSTask()
let pipe = NSPipe()
task.launchPath = "/usr/bin/pmset"
task.arguments = ["-g", "batt"]
task.standardOutput = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
let batteryArray = output.componentsSeparatedByString(";")
let source = output.componentsSeparatedByString("'")[1]
let state = batteryArray[0].stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).capitalizedString
let percent = String.init(batteryArray[0].componentsSeparatedByString(")")[0].stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()))
var remaining = String.init(batteryArray[0].characters.dropFirst().split(" ")[1])
if (remaining == "(no") {
remaining = "Calculating"
}
return [source, state, percent, remaining]
}
}

Passing textFielddata with prepareForSegue as a number and not a string

I am having trouble with the whole string int thing.
I have managed to figure out how to convert each string to a number, however it returns as an optional and when I try to do anything with it I get nil.
My goal is to take 4 inputs from the user.
Each input textField is on separate view controllers.
Each view controller is fed data from variables passed from the view controller before it, using segue prepareForSegue.
Now I get to the last view controller and all the data passes fine, the problem is I cannot do any math with the values held in the variables since they are Strings.
Even after doing the conversion with .int() I cannot do math with them.
This is the last view controller classfile code:
class splitTheBillAmountViewController: UIViewController {
// capture passed data from previous View Controller
var numOfGuests = ""
var subTotalAmount = ""
var taxAmount = ""
var tipAmount = ""
#IBOutlet weak var dynamicTotal: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
println("Split The Bill!”)
// output variables data
println(numOfGuests)
println(subTotalAmount)
println(taxAmount)
println(tipAmount)
// store variables to new name
let string1 = numOfGuests
let string2 = subTotalAmount
let string3 = taxAmount
let string4 = tipAmount
// conversions
let guestNumber : Int? = string1.toInt()
let subTotalNumber : Int? = string2.toInt()
let taxAmountNumber : Int? = string3.toInt()
let tipNumber : Int? = string4.toInt()
// visual to see if numbers are converted .int()
println("\(guestNumber)")
println("\(subTotalNumber)")
println("\(taxAmountNumber)")
println("\(tipNumber)")
// store data to variable
let fTotal : Int? = (guestNumber)
// Update label with total
self.dynamicTotal.text = “fTotal"
// Do any additional setup after loading the view.
}
How can I do math with these variables?
I just need to add them up and divide by var numOfGuests
I'm not sure you want to use Ints for all these values, but that aside I ran this code:
var numOfGuests = "2"
var subTotalAmount = "25"
var taxAmount = "3"
var tipAmount = "2"
let string1 = numOfGuests
let string2 = subTotalAmount
let string3 = taxAmount
let string4 = tipAmount
let guestNumber : Int? = string1.toInt()
let subTotalNumber : Int? = string2.toInt()
let taxAmountNumber : Int? = string3.toInt()
let tipNumber : Int? = string4.toInt()
println("\(guestNumber)")
println("\(subTotalNumber)")
println("\(taxAmountNumber)")
println("\(tipNumber)")
it printed:
Optional(2)
Optional(25)
Optional(3)
Optional(2)
I then modified the print statements to:
println("\(guestNumber!)")
println("\(subTotalNumber!)")
println("\(taxAmountNumber!)")
println("\(tipNumber!)")
It printed:
2
25
3
2
In neither case was the output nil. I think you want to look at how your original strings are getting set. Maybe they're never getting reset from "".
BTW, back to the use of Int types for the calculations, I think you really want to use Float type, not Int.
This code:
var subTotalAmount = "25.15"
let string2 = subTotalAmount
var subTotalNumber = (string2 as NSString).floatValue
println("\(subTotalNumber)")
prints:
25.15
EDIT:
I played with copying your code, and I think you know that you have a typo that the compiler should warn you about. Once I fixed the typo, however I was getting a nil. I got this code to work:
var subTotalAmount = "25.15"
let string2 = subTotalAmount
var subTotalNumber = (string2 as NSString).floatValue
println("\(subTotalNumber)")
let text = NSString(format: "%.2f", subTotalNumber)
println(text)
This prints:
25.15
25.15
EDIT2:
Assuming you have all the numbers as floats, the total bill would be:
var fTotal:Float = subTotalNumber + taxAmountNumber + tipNumber
var costPerGuest:Float = fTotal / guestNumber
let fTotalText = NSString(format: "%.2f", fTotal)
let costPerGuestText = NSString(format: "%.2f", costPerGuest)

Format Numbers in Textfields using Swift

I am trying to format a number from a UITextfield, as its being typed, to a decimal with commas.
I have done so with the following code:
#IBAction func editingDidBegin(sender : AnyObject)
{
costField.addTarget(self, action: Selector("textFieldDidChange:"), forControlEvents: UIControlEvents.EditingChanged)
}
func textFieldDidChange(theTextField:UITextField) -> Void
{
var textFieldText = theTextField.text.stringByReplacingOccurrencesOfString(",", withString: " ", options: NSStringCompareOptions.RegularExpressionSearch, range: Range(start: theTextField.text.startIndex, end: theTextField.text.endIndex))
var formatter:NSNumberFormatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
var formattedOutput = formatter.stringFromNumber(textFieldText.bridgeToObjectiveC().integerValue)
costField.text = formattedOutput
}
The problem with this, is after four digits are entered, everything after the comma is deleted. For example if I enter 4000 it formats to 4,000, then if I type another number like 8 it reformats to 48.
Is there another way I can format this, maybe through IB or how can I fix the code?
Replace the line with:
var textFieldText = theTextField.text.stringByReplacingOccurrencesOfString(",", withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range: Range(start: theTextField.text.startIndex, end: theTextField.text.endIndex))
(I only removed the space between the double quotes).
Fact is, NSNumberFormatter doesn't like the added spaces in the string.
Works fine afterwards.
I know I am late to the party but this worked well for me.
var phoneNumber = " 1 (888) 555-5551 "
var strippedPhoneNumber = "".join(phoneNumber.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet))
It takes out the spaces and strips out the non decimal numeric characters.
The end result is "1888555551"
I've updated this answer to the newest version of swift. This borrows 90% from the two answers above however, also accounts for nil exception from the textfield when the textfield is cleared.
func textFieldDidChangeCommas(theTextField:UITextField) -> Void
{
if theTextField.text != nil {
var textFieldText = theTextField.text!.stringByReplacingOccurrencesOfString(",", withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range: Range(start: theTextField.text!.startIndex, end: theTextField.text!.endIndex))
var formatter:NSNumberFormatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
if textFieldText != "" {
var formattedOutput = formatter.stringFromNumber(Int(textFieldText)!)
costField.text = formattedOutput
}
}
}

Resources