【发布时间】:2014-12-27 05:05:49
【问题描述】:
谁能帮我把它转换成 Swift:
NSAttributedString *attrString = self.attributedText;
NSRange rangeAll = NSMakeRange(0, attrString.length);
// First pass is to check the smallest and largest fontSize so we can prevent changes beyond that.
__block float smallestFontSize = 250;
__block float largestFontSize = 4;
[self.textStorage enumerateAttributesInRange:rangeAll options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:
^(NSDictionary *attributes, NSRange range, BOOL *stop) {
// Iterate over each attribute and look for a Font Size
[attributes enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if ([[key description] isEqualToString:@"NSFont"]) {
UIFont *font = obj;
float fontSize = font.pointSize + bySize;
smallestFontSize = MIN(smallestFontSize, fontSize);
largestFontSize = MAX(largestFontSize, fontSize);
}
}];
}];
编辑:
好的解决了。似乎编译器只是在一段时间内努力解决问题并显示各种语法错误,直到它解决为止。似乎attrs 变量实际上不是NSDictionary 而是一个Swift 字典,所以在你可以使用enumerateKeysandObjectsUsingBlock 之前,有必要将它转换为NSDictionary,这是正确的吗?
如果有更好的方法请告诉我。
var smallestFontSize: CGFloat = 250
var largestFontSize: CGFloat = 4
self.textStorage.enumerateAttributesInRange(rangeAll, options: NSAttributedStringEnumerationOptions.LongestEffectiveRangeNotRequired, usingBlock: {
attrs, range, stop in
FLOG("")
let dict = attrs as NSDictionary
dict.enumerateKeysAndObjectsUsingBlock { key, obj, stop in
if (key.description.isEqual("NSFont")) {
let font = obj as UIFont
let fontSize = font.pointSize + bySize
smallestFontSize = min(smallestFontSize, fontSize);
largestFontSize = max(largestFontSize, fontSize);
}
}
})
【问题讨论】:
-
你有什么事情吗?任何特定的编译器错误?
-
你试过这个转换成swift吗?这是一个非编码转换平台。请在此处提出您的困难或问题。
-
这个问题似乎是题外话,因为它是关于从一种语言翻译成另一种语言。
-
抱歉,我遇到了这么多奇怪的语法错误
-
转换为
NSDictionary然后使用enumerateKeysAndObjecteUsingBlock不是惯用的。你可以改用for (key, value) in dict { ... }。
标签: objective-c swift objective-c-blocks