이미지의 색상만 변경할 수 있다면 얼마나 좋을까? 이를 위해 이것저것 알아보니 틴트컬러 적용을 통해 색상만 변경할 수 있음을 알아냈다.
그래서 틴트컬러를 적용하려 하니 적용되지 않는다.. 뭐가문제지?
let searchOptionButtonImage: UIImageView = {
var imageView = UIImageView()
let image = UIImage(named: "optionIcon")
imageView.image = image
imageView.tintColor = UIColor.white
return imageView
}()
let searchOptionButtonImage: UIImageView = {
var imageView = UIImageView()
let image = UIImage(named: "optionIcon")?.withRenderingMode(.alwaysTemplate)
imageView.image = image
imageView.tintColor = UIColor.white
return imageView
}()
withRenderingMode 는 아래의 세 가지 옵션을 가지고있다.
틴트컬러에 적용하기 위해선 .alwaysOriginal 을 사용하면 된다.
case automatic = 0 // Use the default rendering mode for the context where the image is used
case alwaysOriginal = 1 // Always draw the original image, without treating it as a template
case alwaysTemplate = 2 // Always draw the image as a template image, ignoring its color information요
버튼 이미지에 틴트 컬러를 주는 방법도 꽤나 간단하다.
우선 버튼에는 setImage 라는 매써드로 이미지를 추가하게 되는데 예를 들면 이렇다.
let button: UIButton = {
var button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.titleLabel?.adjustsFontForContentSizeCategory = true
button.setImage(UIImage(named: "optionIcon"), for: .normal)
button.addTarget(self, action: #selector(searchOptionButtonTapped), for: .touchUpInside)
return button
}()
위와 같이 코드를 짜주면 버튼에 이미지가 들어가는데 여기에 위 이미지에 틴트컬러를 넣어줬던 방법처럼 withRenderingMode 매써드를 추가해준 후 틴트컬러를 추가해주면 된다.
let button: UIButton = {
var button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.titleLabel?.adjustsFontForContentSizeCategory = true
button.setImage(UIImage(named: "optionIcon")? .withRenderingMode(.alwaysTemplate), for: .normal)
button.tintColor = .white
button.addTarget(self, action: #selector(searchOptionButtonTapped), for: .touchUpInside)
return button
}()
이렇게 하면 버튼에도 이미지와 틴트컬러를 모두 적용가능하다.