I'm saving some colors picked with a colorPickerView in UserDefaults to display them in a collectionView.
My vc works like this:
You press a cell in the collection view;
The cell's index is collected in userdefaults;
At the same time the colorPickerView is displayed;
The user chooses a color, the picker is dismissed and the color is displayed in a collection view cell;
When I call the methods to dismiss the colorPickerView, I save the picked color with userDefaults and I refresh both the array containing my colors (yes I know it's not recommended but I haven't found a better way to do that yet) and the collection view which displays them. The problem is that after I refresh the array, everything in my view controller doesn't respond anymore to my commands (if I press on my collection view's cells they do nothing).
These are the extensions to save andd retrieve colors with userdefaults:
extension UserDefaults {
func setColor(color: UIColor?, forKey key: String) {
var colorData: NSData?
if let color = color {
do {
colorData = try NSKeyedArchiver.archivedData(withRootObject: color, requiringSecureCoding: false) as NSData?
set(colorData, forKey: key)
} catch let error {
print("error archiving color data", error)
}
}
}
func colorForKey(key: String) -> UIColor? {
var color: UIColor? = .white
if let colorData = data(forKey: key) {
do{
color = try NSKeyedUnarchiver.unarchivedObject(ofClass: UIColor.self, from: colorData)
} catch let error {
print("error unarchivig color data", error)
}
}
return color
}
}
This is how I declare my colors variable:
//Colors
var color1 : UIColor? = UserDefaults.standard.colorForKey(key: Ids.Keys.color1Key)
var color2 : UIColor? = UserDefaults.standard.colorForKey(key: Ids.Keys.color2Key)
var color3 : UIColor? = UserDefaults.standard.colorForKey(key: Ids.Keys.color3Key)
var color4 : UIColor? = UserDefaults.standard.colorForKey(key: Ids.Keys.color4Key)
var colorsArray: [UIColor] = []
This is the function I use every time I want the colorsArray to be refreshed:
func fillColorsArray(){
color1 = UserDefaults.standard.colorForKey(key: Ids.Keys.color1Key)
color2 = UserDefaults.standard.colorForKey(key: Ids.Keys.color2Key)
color3 = UserDefaults.standard.colorForKey(key: Ids.Keys.color3Key)
color4 = UserDefaults.standard.colorForKey(key: Ids.Keys.color4Key)
colorsArray = [color1!, color2!, color3!, color4!]
}
This is the function I call in my colorPickerViewControllerDidFinish:
func checkAndUpdateColor(viewController: UIColorPickerViewController){
passedCellIndex = UserDefaults.standard.integer(forKey: Ids.Keys.passedCellIndexKey)//Index of the tapped collection view cell
switch passedCellIndex {
case 0:
color1 = viewController.selectedColor
UserDefaults.standard.setColor(color: color1, forKey: Ids.Keys.color1Key)
break
case 1:
color2 = viewController.selectedColor
UserDefaults.standard.setColor(color: color2, forKey: Ids.Keys.color2Key)
break
case 2:
color3 = viewController.selectedColor
UserDefaults.standard.setColor(color: color3, forKey: Ids.Keys.color3Key)
break
case 3:
color4 = viewController.selectedColor
UserDefaults.standard.setColor(color: color4, forKey: Ids.Keys.color4Key)
break
default:
break
}
fillColorsArray()
collectionView.reloadData()
}
What causes the problem is the fillColorsArray() function: after calling that, when the picker is dismissed nothing in my view works. However it is the only way I have to display the picked color in my collection view. How can I prevent the fillColorsArray() function from blocking my whole view?
I fixed this by removing the fillColorsArray() function from the checkAndUpdateColor() function. I put it at the top of the collection view's cellForItemAt instead so that it is called when the reloadData function is called.
In my App I want to use stylistic alternate font for 'a' and not system font.
Attaching screenshot which explains the different rendering of the font.
How can I enable this behaviour for UILabel and UITextView so that it renders the correct One Storey 'a'?
I did find a YouTube video link which explains exactly this but he is using a custom font and it is hardcoded. I want to use system font only but with this alternate character.
I might be able to hardcode UILabel with the custom character, I am not sure because I want to use System font. I don't want to use custom Font. What about UITextView which is editable? How can we make it use alternate a as and when the user types?
This is a font feature called "Alternative Stylistic Sets" that you can configure with CoreText. Remember that not all fonts have this option, but the system fonts do. You need to figure out which alternative set you want, however.
First, create the font you're interested in:
import CoreText
import UIKit
let baseFont = UIFont.systemFont(ofSize: 72)
Then print out its features:
print(CTFontCopyFeatures(baseFont)!)
Find the section on Alternative Stylistic Sets, and specifically the set you want, "One storey a:"
{
CTFeatureTypeIdentifier = 35;
CTFeatureTypeName = "Alternative Stylistic Sets";
CTFeatureTypeSelectors = (
{
CTFeatureSelectorIdentifier = 2;
CTFeatureSelectorName = "Straight-sided six and nine";
},
{
CTFeatureSelectorIdentifier = 4;
CTFeatureSelectorName = "Open four";
},
{
CTFeatureSelectorIdentifier = 6;
CTFeatureSelectorName = "Vertically centered colon";
},
{
CTFeatureSelectorIdentifier = 10;
CTFeatureSelectorName = "Vertically compact forms";
},
{
CTFeatureSelectorIdentifier = 12;
CTFeatureSelectorName = "High legibility";
},
{
CTFeatureSelectorIdentifier = 14;
CTFeatureSelectorName = "One storey a";
},
...
The important number is the selector (CTFeatureSelectorIdentifier), 14. With that you can create a new font descriptor and new font:
let descriptor = CTFontDescriptorCreateCopyWithFeature(
baseFont.fontDescriptor,
kStylisticAlternativesType as CFNumber,
14 as CFNumber)
Or you can do this directly in UIKit if it's more convenient:
let settings: [UIFontDescriptor.FeatureKey: Int] = [
.featureIdentifier: kStylisticAlternativesType,
.typeIdentifier: 14
]
let descriptor = baseFont.fontDescriptor.addingAttributes([.featureSettings: [settings]])
(Note the somewhat surprising fact that .featureIdentifier is "CTFeatureTypeIdentifier" and .typeIdentifier is "CTFeatureSelectorIdentifier".)
And then you can create a new font (a zero size means to leave the size the same):
let font = UIFont(descriptor: descriptor, size: 0)
You can use that anywhere that accepts a UIFont.
Here is an extension to simplify choosing an alternative stylistic set for a font, assuming you know its name:
Example usage:
guard let updatedFont = font.withAlternativeStylisticSet(withName: "Alternate y") else {
fatalError("Alternative stylistic set is undefined")
}
UIFont extension:
import UIKit
import CoreText
extension UIFont {
/// Returns the font, applying an alternative stylistic style set.
func withAlternativeStylisticSet(withName name: String) -> UIFont? {
guard let identifier = alternativeStylisticSetIdentifier(withName: name) else {
return nil
}
let settings: [UIFontDescriptor.FeatureKey: Int] = [
.featureIdentifier: kStylisticAlternativesType,
.typeIdentifier: identifier
]
let fontDescriptor = self.fontDescriptor.addingAttributes([.featureSettings: [settings]])
return UIFont(descriptor: fontDescriptor, size: 0)
}
/// Returns the identifier for an alternative stylistic set
private func alternativeStylisticSetIdentifier(withName selectorName: String) -> Int? {
guard let ctFeatures = CTFontCopyFeatures(self) else {
return nil
}
let features = ctFeatures as [AnyObject] as NSArray
for feature in features {
if let featureDict = feature as? [String: Any] {
if let typeName = featureDict[kCTFontFeatureTypeNameKey as String] as? String {
if typeName == "Alternative Stylistic Sets" {
if let featureTypeSelectors = featureDict[kCTFontFeatureTypeSelectorsKey as String] as? NSArray {
for featureTypeSelector in featureTypeSelectors {
if let featureTypeSelectorDict = featureTypeSelector as? [String: Any] {
if let name = featureTypeSelectorDict[kCTFontFeatureSelectorNameKey as String] as? String, let identifier = featureTypeSelectorDict[kCTFontFeatureSelectorIdentifierKey as String] as? Int {
if name == selectorName {
return identifier
}
}
}
}
}
}
}
}
}
return nil
}
}
Heloo.. I am newbie here for ios, swift and xcode...
I have logic in swift file like:
class ExpandableHeaderView: UITableViewHeaderFooterView {
func customInit(menu: Menu, section: Int, delegate: ExpandableHeaderViewDelegate) {
//Create Attachment
let imageAttachment = NSTextAttachment()
var textAfterIcon: NSMutableAttributedString
switch menu {
case .HOME:
imageAttachment.image = UIImage(named:"home")
textAfterIcon = NSMutableAttributedString(string: " Home")
:
}
//Set bound to reposition
let imageOffsetY:CGFloat = -3.0;
imageAttachment.bounds = CGRect(
x: 0,
y: imageOffsetY,
width: imageAttachment.image!.size.width,
height: imageAttachment.image!.size.height)
//Create string with attachmen
let attachmentString = NSAttributedString(attachment: imageAttachment)
//Initialize mutable string
let completeText = NSMutableAttributedString(string: "")
//Add image to mutable string
completeText.append(attachmentString)
//Add your text to mutable string
completeText.append(textAfterIcon)
self.textLabel?.lineBreakMode = NSLineBreakMode.byTruncatingTail
self.textLabel?.attributedText = completeText
:
}
}
But I got result like:
I have added for all NSLineBreakMode.by*, but no one it is prefect to show image and the label: [image] Home
How can I remove 3 dots in the end for textLabel?.attributedText?
It was really confused me...
So, it is my pleasure for anyone can help me...
env:
xCode v. 9.3
I would not consider truncating your labels by "..." as a problem. You should firstly resolve correct sizing of your labels.
I have 3 UiLabels onscreen. I have an array with colors e.g. red,green,blue. I want to set the background of each UiLabel to a a color in the array and then delete the Color from the array so no 2 UiLabels have the same Color.
I was trying to do something like this. it selects a random string in the array but then i cannot assign it to the uilabel because its not of type UIColor.
override func viewDidLoad() {
super.viewDidLoad()
let Colorarray = ["UIColor.redColor()", "UIColor.greenColor()", "UIColor.blueColor()"]
let randomIndex = Int(arc4random_uniform(UInt32(Colorarray.count)))
print(randomIndex)
self.left.text = (Colorarray[randomIndex])
self.left.backgroundColor = (Colorarray[randomIndex])
self.middle.backgroundColor = (Colorarray[randomIndex])
self.right.backgroundColor = (Colorarray[randomIndex])
}
this was the second code i tried
var colorArray = [(UIColor.redColor(), "Red"), (UIColor.greenColor(), "Green"), (UIColor.blueColor(), "Blue")]
//random color
let randomIndex = Int(arc4random_uniform(UInt32(colorArray.count)))
//accessing color
var (color, name) = colorArray[randomIndex]
self.left.text = name
self.left.backgroundColor = color
let leftColorRemoval = (colorArray.removeAtIndex(randomIndex))
print(leftColorRemoval)
var (mcolor, mname) = colorArray[randomIndex]
self.middle.text = mname
self.middle.backgroundColor = mcolor
let middleColorRemoval = (colorArray.removeAtIndex(randomIndex))
print(middleColorRemoval)
var (rcolor, rname) = colorArray[randomIndex]
self.right.text = rname
self.right.backgroundColor = rcolor
let rightColorRemoval = (colorArray.removeAtIndex(randomIndex))
print(rightColorRemoval)
You can store an array of tuples that include both the actual UIColor and the string value. This makes it so you can provide any string value you want:
let colorArray = [(UIColor.redColor(), "Red"), (UIColor.greenColor(), "Green"), (UIColor.blueColor(), "Blue")]
Then, to access a random color:
let (color, name) = colorArray[randomIndex]
self.left.text = name
self.left.backgroundColor = color
...
It seems to me that your code doesn't actually remove random colors. Here's how you would actually do it (one of many ways):
let random = { () -> Int in
return Int(arc4random_uniform(UInt32(colorArray.count)))
} // makes random number, you can make it more reusable
let (leftColor, leftName) = colorArray.removeAtIndex(random()) // removeAtIndex: returns the removed tuple
let (middleColor, middleName) = colorArray.removeAtIndex(random())
let (rightColor, rightName) = colorArray.removeAtIndex(random())
I am currently trying to display some text in Japanese on a UITextView. Is it possible to display the furigana above the kanji (like below) in a manner similar to the < rt> tag in html, without using a web view?
A lot of text processing is involved, therefore I cannot simply use a web view. In iOS8, CTRubyAnnotationRef was added but there is no documentation (I would welcome any example), and I am also concerned with the lack of compatibility with iOS7. I thought that it would be possible to display the furigana above with the use of an NSAttributedString, but couldn't as of yet.
Update Swift 5.1
This solution is an update of preview answers and let you write Asian sentences with Phonetic Guide, using a pattern in the strings.
Let's start from handling string.
these 4 extension let you to inject in a string the ruby annotation.
the function createRuby() check the string a pattern, that it is: |word written in kanji《phonetic guide》.
Examples:
|紅玉《ルビー》
|成功《せいこう》するかどうかは、きみの|努力《どりょく》に|係《かか》る。
and so on.
the important thing is to follow the pattern.
extension String {
// 文字列の範囲
private var stringRange: NSRange {
return NSMakeRange(0, self.utf16.count)
}
// 特定の正規表現を検索
private func searchRegex(of pattern: String) -> NSTextCheckingResult? {
do {
let patternToSearch = try NSRegularExpression(pattern: pattern)
return patternToSearch.firstMatch(in: self, range: stringRange)
} catch { return nil }
}
// 特定の正規表現を置換
private func replaceRegex(of pattern: String, with templete: String) -> String {
do {
let patternToReplace = try NSRegularExpression(pattern: pattern)
return patternToReplace.stringByReplacingMatches(in: self, range: stringRange, withTemplate: templete)
} catch { return self }
}
// ルビを生成
func createRuby() -> NSMutableAttributedString {
let textWithRuby = self
// ルビ付文字(「|紅玉《ルビー》」)を特定し文字列を分割
.replaceRegex(of: "(|.+?《.+?》)", with: ",$1,")
.components(separatedBy: ",")
// ルビ付文字のルビを設定
.map { component -> NSAttributedString in
// ベース文字(漢字など)とルビをそれぞれ取得
guard let pair = component.searchRegex(of: "|(.+?)《(.+?)》") else {
return NSAttributedString(string: component)
}
let component = component as NSString
let baseText = component.substring(with: pair.range(at: 1))
let rubyText = component.substring(with: pair.range(at: 2))
// ルビの表示に関する設定
let rubyAttribute: [CFString: Any] = [
kCTRubyAnnotationSizeFactorAttributeName: 0.5,
kCTForegroundColorAttributeName: UIColor.darkGray
]
let rubyAnnotation = CTRubyAnnotationCreateWithAttributes(
.auto, .auto, .before, rubyText as CFString, rubyAttribute as CFDictionary
)
return NSAttributedString(string: baseText, attributes: [kCTRubyAnnotationAttributeName as NSAttributedString.Key: rubyAnnotation])
}
// 分割されていた文字列を結合
.reduce(NSMutableAttributedString()) { $0.append($1); return $0 }
return textWithRuby
}
}
Ruby Label: the big problem
As you maybe know, Apple has introduced in iOS 8 the ruby annotation like attribute for the attributedString, and if you did create the the attributed string with ruby annotation and did:
myLabel.attributedText = attributedTextWithRuby
the label did shows perfectly the string without problem.
From iOS 11, Apple unfortunately has removed this feature and, so, if want to show ruby annotation you have override the method draw, to effectively draw the text. To do this, you have to use Core Text to handle the text hand it's lines.
Let's show the code
import UIKit
public enum TextOrientation { //1
case horizontal
case vertical
}
class RubyLabel: UILabel {
public var orientation:TextOrientation = .horizontal //2
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
// ルビを表示
override func draw(_ rect: CGRect) {
//super.draw(rect) //3
// context allows you to manipulate the drawing context (i'm setup to draw or bail out)
guard let context: CGContext = UIGraphicsGetCurrentContext() else {
return
}
guard let string = self.text else { return }
let attributed = NSMutableAttributedString(attributedString: string.createRuby()) //4
let path = CGMutablePath()
switch orientation { //5
case .horizontal:
context.textMatrix = CGAffineTransform.identity;
context.translateBy(x: 0, y: self.bounds.size.height);
context.scaleBy(x: 1.0, y: -1.0);
path.addRect(self.bounds)
attributed.addAttribute(NSAttributedString.Key.verticalGlyphForm, value: false, range: NSMakeRange(0, attributed.length))
case .vertical:
context.rotate(by: .pi / 2)
context.scaleBy(x: 1.0, y: -1.0)
//context.saveGState()
//self.transform = CGAffineTransform(rotationAngle: .pi/2)
path.addRect(CGRect(x: self.bounds.origin.y, y: self.bounds.origin.x, width: self.bounds.height, height: self.bounds.width))
attributed.addAttribute(NSAttributedString.Key.verticalGlyphForm, value: true, range: NSMakeRange(0, attributed.length))
}
attributed.addAttributes([NSAttributedString.Key.font : self.font], range: NSMakeRange(0, attributed.length))
let frameSetter = CTFramesetterCreateWithAttributedString(attributed)
let frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0,attributed.length), path, nil)
// Check need for truncate tail
//6
if (CTFrameGetVisibleStringRange(frame).length as Int) < attributed.length {
// Required truncate
let linesNS: NSArray = CTFrameGetLines(frame)
let linesAO: [AnyObject] = linesNS as [AnyObject]
var lines: [CTLine] = linesAO as! [CTLine]
let boundingBoxOfPath = path.boundingBoxOfPath
let lastCTLine = lines.removeLast() //7
let truncateString:CFAttributedString = CFAttributedStringCreate(nil, "\u{2026}" as CFString, CTFrameGetFrameAttributes(frame))
let truncateToken:CTLine = CTLineCreateWithAttributedString(truncateString)
let lineWidth = CTLineGetTypographicBounds(lastCTLine, nil, nil, nil)
let tokenWidth = CTLineGetTypographicBounds(truncateToken, nil, nil, nil)
let widthTruncationBegins = lineWidth - tokenWidth
if let truncatedLine = CTLineCreateTruncatedLine(lastCTLine, widthTruncationBegins, .end, truncateToken) {
lines.append(truncatedLine)
}
var lineOrigins = Array<CGPoint>(repeating: CGPoint.zero, count: lines.count)
CTFrameGetLineOrigins(frame, CFRange(location: 0, length: lines.count), &lineOrigins)
for (index, line) in lines.enumerated() {
context.textPosition = CGPoint(x: lineOrigins[index].x + boundingBoxOfPath.origin.x, y:lineOrigins[index].y + boundingBoxOfPath.origin.y)
CTLineDraw(line, context)
}
}
else {
// Not required truncate
CTFrameDraw(frame, context)
}
}
//8
override var intrinsicContentSize: CGSize {
let baseSize = super.intrinsicContentSize
return CGSize(width: baseSize.width, height: baseSize.height * 1.0)
}
}
Code explanation:
1- Chinese and japanese text can be written in horizontal and vertical way. This enumeration let you switch in easy way between horizontal and vertical orietantation.
2- public variable with switch orientation text.
3- this method must be commented. the reason is that call it you see two overlapping strings:one without attributes, last your attributed string.
4- here call the method of String class extension in which you create the attributed string with ruby annotation.
5- This switch, rotate if need the context in which draw your text in case you want show vertical text. In fact in this switch you add the attribute NSAttributedString.Key.verticalGlyphForm that in case vertical is true, false otherwise.
6- This 'if' is particular important because, the label, cause we had commented the method 'super.draw()' doesn't know how to manage a long string. without this 'if', the label thinks to have only one line to draw. And so, you still to have a string with '...' like tail. In this 'if' the string is broken in more line and drawing correctly.
7- When you don't give to label some settings, the label knows to have more one line but because it can't calculate what is the showable last piece of string, give error in execution time and the app goes in crash. So be careful. But, don't worry! we talk about the right settings to give it later.
8- this is very important to fit the label to text's size.
How to use the RubyLabel
the use of the label is very simple:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var rubyLabel: RubyLabel! //1
override func viewDidLoad() {
super.viewDidLoad()
setUpLabel()
}
private func setUpLabel() {
rubyLabel.text = "|成功《せいこう》するかどうかは、きみの|努力《どりょく》に|係《かか》る。|人々《ひとびと》の|生死《せいし》に|係《かか》る。" //2
//3
rubyLabel.textAlignment = .left
rubyLabel.font = .systemFont(ofSize: 20.0)
rubyLabel.orientation = .horizontal
rubyLabel.lineBreakMode = .byCharWrapping
}
}
Code Explanation:
1- connect label to xib if use storyboard or xib file or create label.
2- as I say, the use is very simple: here assign the string with ruby pattern like any other string
3- these setting are the setting to have to set to make work the label. You can set via code or via storyboard/xib
Be careful
if you use storyboard/xib, if you don't put correctly the constraints, the label give you the error at point n° 7.
Result
Works, but not perfect
As you can see by screenshot, this label work well but still has some problem.
1- with vertical text the label still in horizontal shape;
2- if the string contains \n to split the string in more lines, the label shows only the number of lines that the string would have had if was without the '\n' character.
I'm working for fix these problem, but your help is appreciated.
In the end I created a function that gets the kanji's position and create labels every time, above the kanji. It's quite dirty but it's the only way to insure a compatibility with iOS7.
However I have to mention the remarkable examples that you can find on GitHub for the CTRubyAnnotationRef nowadays like : http://dev.classmethod.jp/references/ios8-ctrubyannotationref/
and
https://github.com/shinjukunian/SimpleFurigana
Good luck to all of you !
Here's a focused answer with some comments. This works for UITextView and UILabel on iOS 16.
let rubyAttributes: [CFString : Any] = [
kCTRubyAnnotationSizeFactorAttributeName : 0.5,
kCTRubyAnnotationScaleToFitAttributeName : 0.5,
]
let annotation = CTRubyAnnotationCreateWithAttributes(
.center, // Alignment relative to base text
.auto, // Overhang for adjacent characters
.before, // `before` = above, `after` = below, `inline` = after the base text (for horizontal text)
"Ruby!" as CFString,
rubyAttributes as CFDictionary
)
let stringAttributes = [kCTRubyAnnotationAttributeName as NSAttributedString.Key : annotation]
NSAttributedString(string: "Base Text!", attributes: stringAttributes)
Note, you may want to UITextView.textContainerInset.top to something larger than the default to avoid having the ruby clipped by the scrollview.