Here's another way to set the alignment for an NSTextAttachment image. Hope this also helps someone deal with this. I use the following code in func tableView (_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
var buttonText = "My Button"; let align = NSMutableParagraphStyle(); align.alignment = NSTextAlignment.center; align.firstLineHeadIndent = 10.0; align.headIndent = 10.0; align.tailIndent = -10.0; let para = NSMutableAttributedString(); // top padding para.append(NSAttributedString(string: "\n", attributes: [NSParagraphStyleAttributeName: align, NSFontAttributeName: UIFont(name: "Helvetica", size: 10.0)!, NSForegroundColorAttributeName: UIColor.white])); // image let img = NSTextAttachment(); img.image = UIImage(named: "MyIcon"); img.bounds = CGRect(x: 0, y: UIFont(name: "Helvetica", size: 18.0)!.descender, width: img.image!.size.width, height: img.image!.size.height); let nas = NSAttributedString(attachment: img).mutableCopy() as! NSMutableAttributedString; nas.addAttribute(NSParagraphStyleAttributeName, value: align, range: NSRange(location: 0, length: nas.length)); para.append(nas); // space to text buttonText = " " + buttonText; // text para.append(NSAttributedString( string: buttonText, attributes: [NSParagraphStyleAttributeName: align, NSFontAttributeName: UIFont(name: "Helvetica", size: 18.0)!, NSForegroundColorAttributeName: UIColor.black])); // bottom padding para.append(NSAttributedString(string: "\n", attributes: [NSParagraphStyleAttributeName: align, NSFontAttributeName: UIFont(name: "Helvetica", size: 10.0)!, NSForegroundColorAttributeName: UIColor.white])); // set cell label let label = cell.textLabel!; label.numberOfLines = 0; label.layer.borderWidth = 0; label.layer.masksToBounds = false; label.backgroundColor = UIColor.clear; label.layer.backgroundColor = UIColor.green; label.attributedText = para;
source share