2015-12-04 22 views
7

Tôi có một chuỗi không có khoảng trống ở cuối chuỗi nhưng khi tôi chuyển đổi thành NSAttributedString và đặt thành UITextView, nó đã được xem một số khoảng trắng ở cuối UILabel .Cách cắt (xóa) khoảng trắng từ cuối NSAttributedString

Để thực hiện NSAttributedString Tôi đang sử dụng mã sau đây. Trong mã của tôi expectedLabelSize cho một chiều cao lớn.

UILabel *tempLbl = [[UILabel alloc]init]; 
tempLbl.font = txtView.font; 
tempLbl.text = string; 

NSDictionary *dictAttributes = [NSDictionary dictionaryWithObjectsAndKeys: tempLbl.font, NSFontAttributeName, aParaStyle, NSParagraphStyleAttributeName,[UIColor darkGrayColor],NSForegroundColorAttributeName, nil]; 

CGSize expectedLabelSize = [string boundingRectWithSize:maximumLabelSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dictAttributes context: nil].size; 
+0

Cập nhật câu hỏi của bạn bằng mã khởi tạo 'chuỗi'. Tại sao câu hỏi của bạn nói về 'UITextView'? Mã được đăng của bạn không đề cập đến chế độ xem văn bản. Và 'UILabel' phải làm gì với câu hỏi? Nó không có dấu hiệu trên 'expectedLabelSize'. – rmaddy

+0

Bạn đã thử đặt thành 0 rồi làm sizeToFit? –

Trả lời

7

Swift câu trả lời nhưng nó cung cấp cho bạn một sự khởi đầu nếu bạn dịch nó để obj-C (hoặc thực hiện một tập tin nhanh chóng chỉ với phần mở rộng để sử dụng với obj-C sau đó)

extension NSMutableAttributedString { 

    func trimmedAttributedString(set: CharacterSet) -> NSMutableAttributedString { 

     let invertedSet = set.inverted 

     var range = (string as NSString).rangeOfCharacter(from: invertedSet) 
     let loc = range.length > 0 ? range.location : 0 

     range = (string as NSString).rangeOfCharacter(
          from: invertedSet, options: .backwards) 
     let len = (range.length > 0 ? NSMaxRange(range) : string.characters.count) - loc 

     let r = self.attributedSubstring(from: NSMakeRange(loc, len)) 
     return NSMutableAttributedString(attributedString: r) 
    } 
} 

Cách sử dụng :

let noSpaceAttributedString = 
    attributedString.trimmedAttributedString(set: CharacterSet.whitespacesAndNewlines) 
+0

Cảm ơn Dean, tuyệt vời. Tôi đã chỉnh sửa trong các thay đổi nhỏ cho Swift mới nhất. Thật sự cảm ơn – Fattie

Các vấn đề liên quan