Edited at

Swift 丸アイコン内、テキストセンター描画

More than 3 years have passed since last update.


Swift 丸アイコン内、テキストセンター描画

UIViewのカスタムクラスにて、overrideしたdrawRect内で、

// 丸描画

let roundRect = UIBezierPath(roundedRect: CGRectMake(1, 1, 28, 28), cornerRadius: 10)
UIColor.blueColor().setStroke()
roundRect.lineWidth = 2
roundRect.stroke()

// フォント属性
let fontAttr = [NSFontAttributeName: UIFont.systemFontOfSize(10)]
// テキスト
let str = self.initial_txt! as NSString!
// サイズ取得
let size = str.sizeWithAttributes(fontAttr)

let x_pos = (roundRect.bounds.size.width - size.width) / 2
let y_pos = (roundRect.bounds.size.height - size.height) / 2

// テキスト描画
str.drawAtPoint(CGPointMake(roundRect.bounds.origin.x + x_pos, roundRect.bounds.origin.y + y_pos),
withAttributes: fontAttr)


結果


参考

How to use NSString drawInRect to center text?

http://stackoverflow.com/questions/477509/how-to-use-nsstring-drawinrect-to-center-text