我有一個問題,「boundingRectForGlyphRange」總是返回CGRect.zero「0.0,0.0,0.0,0.0」。 「boundingRectForGlyphRange」不起作用。例如,我正在編寫觸摸UILabel功能部分文本的代碼。我的文本的第一部分是「任何文本」,第二部分是「閱讀更多」。當我觸摸「閱讀更多」時,我只需要輕觸識別器就可以工作。如果我用手觸摸的UILabel的任何一點,「CGRectContainsPoint」總是返回true,那麼行動稱爲Swift:點擊UILabel文本的一部分
這裏我的代碼:
override func viewDidLoad() {
super.viewDidLoad()
// The full string
let firstPart:NSMutableAttributedString = NSMutableAttributedString(string: "Lorem ipsum dolor set amit ", attributes: [NSFontAttributeName: UIFont.systemFontOfSize(13)])
firstPart.addAttribute(NSForegroundColorAttributeName, value: UIColor.blackColor(),
range: NSRange(location: 0, length: firstPart.length))
info.appendAttributedString(firstPart)
// The "Read More" string that should be touchable
let secondPart:NSMutableAttributedString = NSMutableAttributedString(string: "READ MORE", attributes: [NSFontAttributeName: UIFont.systemFontOfSize(14)])
secondPart.addAttribute(NSForegroundColorAttributeName, value: UIColor.blackColor(),
range: NSRange(location: 0, length: secondPart.length))
info.appendAttributedString(secondPart)
lblTest.attributedText = info
// Store range of chars we want to detect touches for
moreStringRange = NSMakeRange(firstPart.length, secondPart.length)
print("moreStringRange\(moreStringRange)")
tapRec.addTarget(self, action: "didTap:")
lblTest.addGestureRecognizer(tapRec)
}
func didTap(sender:AnyObject) {
// Storage class stores the string, obviously
let textStorage:NSTextStorage = NSTextStorage(attributedString: info)
// The storage class owns a layout manager
let layoutManager:NSLayoutManager = NSLayoutManager()
textStorage.addLayoutManager(layoutManager)
// Layout manager owns a container which basically
// defines the bounds the text should be contained in
let textContainer:NSTextContainer = NSTextContainer(size: lblTest.frame.size)
textContainer.lineFragmentPadding = 0
textContainer.lineBreakMode = lblTest.lineBreakMode
// Begin computation of actual frame
// Glyph is the final display representation
var glyphRange = NSRange()
// Extract the glyph range
layoutManager.characterRangeForGlyphRange(moreStringRange!, actualGlyphRange: &glyphRange)
// Compute the rect of glyph in the text container
print("glyphRange\(glyphRange)")
print("textContainer\(textContainer)")
let glyphRect:CGRect = layoutManager.boundingRectForGlyphRange(glyphRange, inTextContainer: textContainer)
// Final rect relative to the textLabel.
print("\(glyphRect)")
// Now figure out if the touch point is inside our rect
let touchPoint:CGPoint = tapRec.locationOfTouch(0, inView: lblTest)
if CGRectContainsPoint(glyphRect, touchPoint) {
print("User tapped on Read More. So show something more")
}
}
它只是爲了測試我想要做一個演示:
任何幫助將不勝感激。
希望這會幫助你[閱讀更多](http:// stackoverflow。com/questions/32309247/add-read-up-of-the-end-of-uilabel) – iMuzahid
如何使用兩個標籤? – Koen
@Koen:這只是一個演示。我的文字有許多附件。我不能使用很多標籤。 – Ashley