I am getting an error when trying to set a tag color Blue to a file using setResourceValue:
var error: NSError?
let listofTags = NSWorkspace.sharedWorkspace().fileLabels
let theURL:NSURL = NSURL.fileURLWithPath("/Volumes/234567_fr.tif")!
var Tag: AnyObject = NSWorkspace.sharedWorkspace().fileLabels[4] // Tag = "Blue"
theURL.setResourceValue(Tag, forKey: NSURLTagNamesKey, error: &error)
println(error) // Error Domain=NSOSStatusErrorDomain Code=-8050 "The operation couldn’t be completed. (OSStatus error -8050.)
Any idea? Thank you for your help
Solution:
1 - The first argument for setResourceValue has to be an NSArray
2 - Shocking, but... the color name has to be the localized one!
This example fixes your error 8050 but doesn't actually set a color tag if your system language isn't English:
var error: NSError?
let theURL:NSURL = NSURL(fileURLWithPath: "/Users/me/tests/z.png")!
let tag: AnyObject = NSWorkspace.sharedWorkspace().fileLabels[4] // "Blue" tag
let arr = NSArray(object: tag)
theURL.setResourceValue(arr, forKey: NSURLTagNamesKey, error: &error)
On my system (French), this doesn't set an actual blue color label tag, only a text tag containing the word "Blue".
To set the proper color tag, you have to give the localized color name literally:
var error: NSError?
let theURL:NSURL = NSURL(fileURLWithPath: "/Users/me/tests/z.png")!
let arr = NSArray(object: "Bleu") // "Blue" translated to French
theURL.setResourceValue(arr, forKey: NSURLTagNamesKey, error: &error)
Related
I'm trying to save images retrieved from Parse.com like this:
let userImageFile = object["Image"] as PFFile
userImageFile.getDataInBackgroundWithBlock {
(imageData: NSData!, error: NSError!) -> Void in
if error == nil {
image = UIImage(data:imageData)
let imageToSave:NSData = UIImagePNGRepresentation(image)
self.saveImage(intRandomNumb, retImage: imageToSave)
}
}
where the saveImage-function looks like this:
func saveImage(imagepath:Int, retImage:NSData){
println("image is being saved")
let defaults = NSUserDefaults.standardUserDefaults()
let imagePathName = "\(imagepath)"
defaults.setObject(retImage, forKey: imagePathName)
}
and later, I'm trying to display this image like this:
var point = gestureRecognizer.locationInView(self.tv)
if let indexPath = self.tv.indexPathForRowAtPoint(point)
{
let data = mainList[indexPath.row] as SecondModel
let fileRef = data.fileReference
let intFileRef = Int(fileRef)
println(intFileRef)
let defaults = NSUserDefaults.standardUserDefaults()
let usedKeyName = "\(intFileRef)"
if let photo = defaults.objectForKey(usedKeyName) as? UIImage {
println("Image created")
let photo = defaults.objectForKey(usedKeyName) as UIImage
var imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height))
imageView.image = photo
self.view.addSubview(imageView)
}
and the "Image created" never gets printed which means the retrieving somehow doesn't work.
I'm not quite sure if you're able to save images to the userdefaults like I've done here, but that was the best I could come up with, and I couldn't find any previous questions like this for Swift.
Any suggestions on how to proceed would be appreciated.
SOLUTION: The problem was that I tried to load the image directly as a UIImage. I also had to convert the NSData to a UIImage, this all happens in the last section of the code displayed above. Finally my code looks like this:
if let photo = defaults.objectForKey("\(intFileRef)") as? NSData {
println("Image created")
let photo = defaults.objectForKey("\(intFileRef)") as NSData
let imageToView:UIImage = UIImage(data: photo)
var imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height))
imageView.image = imageToView
self.view.addSubview(imageView)
}
I hope this can help others struggling with something similar to this.
Swift 3
Hey, try this beautiful code here:
Convert your UIImage to Data.
PNG:
yourDataImagePNG = UIImagePNGRepresentation(yourUIImageHere)
JPEG :
yourDataImageJPG = UIImage(data: yourUIImageHere,scale:1.0)
Save in UserDefaults.
UserDefaults().set(yourDataImagePNG, forKey: "image")
Recover from:
UserDefaults.standard.object(forKey: "image") as! Data
I hope to help!
It seems like you do not call defaults.synchronize() so it's not written to the defaults file.
So i was trying to get some information about my usb devices and all of them seem to have the same output for NSURLVolumeIsRemovableKey, NSURLVolumeIsEjectableKey, and NSURLVolumeIsReadOnlyKey. I do see the different key names and correct volume sizes, is there an issue with my code? or is this something else?
var filemanager: NSFileManager = NSFileManager()
var keys: NSArray = [NSURLVolumeNameKey, NSURLVolumeIsRemovableKey,NSURLVolumeIsEjectableKey,NSURLVolumeIsReadOnlyKey,NSURLVolumeMaximumFileSizeKey]
var url = filemanager.mountedVolumeURLsIncludingResourceValuesForKeys(keys, options: nil)!
for items in url
{
var a: AnyObject?
var b: AnyObject?
var c: AnyObject?
var d: AnyObject?
var e: AnyObject?
var err: NSError?
items.getPromisedItemResourceValue(&a, forKey: NSURLVolumeNameKey, error: &err)
items.getPromisedItemResourceValue(&b, forKey: NSURLVolumeIsRemovableKey, error: &err)
items.getPromisedItemResourceValue(&c, forKey: NSURLVolumeIsEjectableKey, error: &err)
items.getPromisedItemResourceValue(&d, forKey: NSURLVolumeIsReadOnlyKey, error: &err)
items.getPromisedItemResourceValue(&e, forKey: NSURLVolumeMaximumFileSizeKey, error: &err)
println("itemname: \(items)")
println(a!)
println(b!)
println(c!)
println(d!)
println(e)
}
Running Xcode 6 Beta 7,
I'm trying to unwrap a dictionary called detail, with a key categories which is an array of category dictionaries. Each category is of type [String : AnyObject]
var category: [String: AnyObject] = detail!["categories"]![categoryIndex] as [String: AnyObject]
I get the error
Operand of Postfix "!" should have optional type, type is '(String, AnyObject)'
If I remove the exclamation point "!" as the compiler suggested
var category: [String: AnyObject] = detail!["categories"][categoryIndex] as [String: AnyObject]
I get the error
(String, AnyObject) does not have the member named `subscript`
Help!
Here is my detail declaration
var detail: [String : AnyObject]?
The problem seems to be that the compiler can't figure out how to cast the various AnyObjects when accessing them like that. You can get around it with some creative inline casting:
var category: [String: AnyObject]? = ((detail?["categories"] as AnyObject?) as? [[String: AnyObject]])?[categoryIndex]
It would nicer to separate those steps out though:
var categoriesObj: AnyObject? = detail?["categories"]
var categories: [[String: AnyObject]]? = categoriesObj as? [[String: AnyObject]]
var category: [String: AnyObject]? = categories?[categoryIndex]
Note: I had to change category to an [String: AnyObject]?
I try to change the placeholder text color. This code doesn't work:
let color = NSColor.redColor()
let attrs = [NSForegroundColorAttributeName: color]
let placeHolderStr = NSAttributedString(string: "My placeholder", attributes: attrs)
myTextField.placeholderAttributedString = placeHolderStr
I get the error -[NSTextField setPlaceholderAttributedString:]: unrecognized selector sent to instance. Any ideas, how I can change the color of the placeholder?
UPDATE:
This works:
(myTextField.cell() as NSTextFieldCell).placeholderAttributedString = placeHolderStr
UPDATE 2:
Hmm, it changes the color, but if the text field gets the focus, the placeholder font size get's smaller, very strange.
By explicitly defining the font of the NSAttributedString, the placeholder font resizing referred to in the original question is fixed.
The following is a working example in Swift 3.0.
let color = NSColor.red
let font = NSFont.systemFont(ofSize: 14)
let attrs = [NSForegroundColorAttributeName: color, NSFontAttributeName: font]
let placeholderString = NSAttributedString(string: "My placeholder", attributes: attrs)
(textField.cell as? NSTextFieldCell)?.placeholderAttributedString = placeholderString
The following is a working example in Swift 4.2.
let attrs = [NSAttributedString.Key.foregroundColor: NSColor.lightGray,
NSAttributedString.Key.font: NSFont.systemFont(ofSize: 14)]
let placeholderString = NSAttributedString(string: "My placeholder", attributes: attrs)
(taskTextField.cell as? NSTextFieldCell)?.placeholderAttributedString = placeholderString
You should set the placeholder text in NSTextFieldCell and not NSTextField.
myTextField.cell.placeholderAttributedString = placeHolderStr
You should keep current font, and current value from IB
extension NSTextField {
func setHintTextColor (color: NSColor) {
let currentHint = placeholderString ?? ""
let placeholderAttributes: [NSAttributedString.Key: Any] = [
NSAttributedString.Key.foregroundColor: color,
NSAttributedString.Key.font: font!
]
let placeholderAttributedString = NSMutableAttributedString(string: currentHint, attributes: placeholderAttributes)
let paragraphStyle = NSMutableParagraphStyle()
placeholderAttributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0,length: placeholderAttributedString.length))
self.placeholderAttributedString = placeholderAttributedString
}
}
I've got several UILabels with multiple lines of text, but the line spacing is larger than I would prefer. Is there any way to change this?
hi this is a late reply but it may help some one line height can be change change the text from plain to attribute
Since iOS 6, Apple added NSAttributedString to UIKit, making it possible to use NSParagraphStyle to change the line spacing.
To actually change it from NIB, please see souvickcse's answer.
Because I friggin hate using attributed text in interface builder (I always run into IB bugs), here is an extension to allow you to set line height multiple directly to a UILabel in interface builder
extension UILabel {
#IBInspectable
var lineHeightMultiple: CGFloat {
set{
//get our existing style or make a new one
let paragraphStyle: NSMutableParagraphStyle
if let existingStyle = attributedText?.attribute(NSAttributedString.Key.paragraphStyle, at: 0, effectiveRange: .none) as? NSParagraphStyle, let mutableCopy = existingStyle.mutableCopy() as? NSMutableParagraphStyle {
paragraphStyle = mutableCopy
} else {
paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 1.0
paragraphStyle.alignment = self.textAlignment
}
paragraphStyle.lineHeightMultiple = newValue
//set our text from existing text
let attrString = NSMutableAttributedString()
if let text = self.text {
attrString.append( NSMutableAttributedString(string: text))
attrString.addAttribute(NSAttributedString.Key.font, value: self.font, range: NSMakeRange(0, attrString.length))
}
else if let attributedText = self.attributedText {
attrString.append( attributedText)
}
//add our attributes and set the new text
attrString.addAttribute(NSAttributedString.Key.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attrString.length))
self.attributedText = attrString
}
get {
if let paragraphStyle = attributedText?.attribute(NSAttributedString.Key.paragraphStyle, at: 0, effectiveRange: .none) as? NSParagraphStyle {
return paragraphStyle.lineHeightMultiple
}
return 0
}
}