環境
- iPhone8
- iOS13.1 β2
原因
-
self.textColor
への設定では反応しなくなった - Storyboardで色の指定がデフォルトだとライト、ダークモードに適した文字色になる
iOS12までで動いていたコード
- UILabelをOverrideしたOutlineLabelを作っていた
before.swift
public class OutlineLabel: UILabel {
// MARK: - Public Properties
public var outlineColor: UIColor = .white {
didSet {
setNeedsDisplay()
}
}
public var outlineSize: CGFloat = 2 {
didSet {
setNeedsDisplay()
}
}
override public func drawText(in rect: CGRect) {
guard let attrString = attributedText else { return }
guard let context = UIGraphicsGetCurrentContext() else { return }
let orgColor = textColor
context.saveGState()
context.setLineWidth(outlineSize)
context.setLineJoin(.round)
context.setTextDrawingMode(.stroke)
textColor = outlineColor
attrString.draw(in: rect)
context.restoreGState()
context.saveGState()
textColor = orgColor
context.setTextDrawingMode(.fill)
attrString.draw(in: rect)
context.restoreGState()
}
}
iOS13で動くようになったコード
- 文字色の指定はaddAttributesで行うようにする
after.swift
public class OutlineLabel: UILabel {
// MARK: - Public Properties
public var outlineColor: UIColor = .white {
didSet {
setNeedsDisplay()
}
}
public var outlineSize: CGFloat = 2 {
didSet {
setNeedsDisplay()
}
}
override public func drawText(in rect: CGRect) {
guard let attrStringBase = attributedText else { return }
guard let context = UIGraphicsGetCurrentContext() else { return }
guard let orgColor = textColor else { return }
if #available(iOS 13, *) {
let attrString = NSMutableAttributedString(attributedString: attrStringBase)
attrString.addAttributes (
[NSAttributedString.Key.foregroundColor: self.outlineColor
], range: NSRange(location: 0, length: attrString.length))
context.saveGState()
context.setLineWidth(outlineSize)
context.setLineJoin(.round)
context.setTextDrawingMode(.stroke)
attrString.draw(in: rect)
context.restoreGState()
attrString.addAttributes (
[NSAttributedString.Key.foregroundColor: orgColor
], range: NSRange(location: 0, length: attrString.length))
context.saveGState()
context.setTextDrawingMode(.fill)
attrString.draw(in: rect)
context.restoreGState()
} else {
let attrString = attrStringBase
textColor = outlineColor
context.saveGState()
context.setLineWidth(outlineSize)
context.setLineJoin(.round)
context.setTextDrawingMode(.stroke)
attrString.draw(in: rect)
context.restoreGState()
context.saveGState()
textColor = orgColor
context.setTextDrawingMode(.fill)
attrString.draw(in: rect)
context.restoreGState()
}
}
}
}