Rodhos Soft

備忘録を兼ねた技術的なメモです。Rofhos SoftではiOSアプリ開発を中心としてAndroid, Webサービス等の開発を承っております。まずはご相談下さい。

AttributeString

以下のサンプルコードを見れば大体わかると思う。

  override func viewWillAppear(animated: Bool) {
        
        let str = "はろー World"
        let attrStr = NSMutableAttributedString(string: str)
        
        // フォント設定 http://iosfonts.com/
        attrStr.addAttribute(NSFontAttributeName, value: UIFont(name: "Futura-CondensedMedium",size: 17.0)!, range: NSRange(location: 0, length: attrStr.length))
        
        
        // 背景色
        attrStr.addAttribute(NSBackgroundColorAttributeName, value: UIColor(red: 1.0, green: 0.5, blue: 0.5, alpha: 1.0), range: NSRange(location: 0, length: attrStr.length))
        
        // 文字色
        attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0), range: NSRange(location: 0, length: attrStr.length))
        
        // 打ち消し戦
        attrStr.addAttribute(NSStrikethroughColorAttributeName, value: NSNumber(int: 3), range:NSRange(location: 0, length: attrStr.length))
        
        // 影
        let shadow = NSShadow()
        shadow.shadowColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1)
        shadow.shadowBlurRadius = 3
        shadow.shadowOffset = CGSize(width: 1, height: 1)
        
        attrStr .addAttribute(NSShadowAttributeName, value: shadow, range: NSRange(location: 0, length: attrStr.length))
        
        // 中抜き NSStrokeWidthAttributeName
        // 下線 NSUnderlineStyleAttributeName
        // カーニング NSKernAttributeName
        
        // パラグラフの調整
        let paragraph = NSMutableParagraphStyle()
        paragraph.alignment = NSTextAlignment.Left
        paragraph.hyphenationFactor = 0.9 // 行末で切れる単語を-でつなぐ
        paragraph.lineSpacing = 1.0
        paragraph.lineHeightMultiple = 1.5
        
        attrStr.addAttribute(NSParagraphStyleAttributeName, value: paragraph, range: NSRange(location: 0, length: attrStr.length))
        
        
        // 画像を加える
        let textAttachment = NSTextAttachment()
        let image = UIImage(named: "a")!
        textAttachment.image = image
        textAttachment.bounds = CGRect(origin: CGPointZero, size: image.size)
        let appendStr = NSAttributedString(attachment: textAttachment)
        
        attrStr.appendAttributedString(appendStr)
        
        self.textView.attributedText = attrStr;

        
    }