【发布时间】:2017-11-20 20:06:45
【问题描述】:
嘿嘿,
几天以来,我尝试创建“材料设计芯片”,但只成功了一半。
我最成功的尝试是从“Button”创建一个子类(Button 是 UIButton 的一个子类,由 cosmicmind 在他的 MaterialDesign-Framework for swift 中创建)。
对于不知道我指的是“筹码”的人:click here
我的例子:
简单/不可删除的芯片
import UIKit
import Material
class ChipButton: Button {
override func prepare() {
super.prepare()
cornerRadiusPreset = .cornerRadius5
backgroundColor = UIColor.lightGray
titleColor = Color.darkText.primary
pulseAnimation = .none
contentEdgeInsets = EdgeInsets(top: 0, left: 12, bottom: 0, right: 12)
isUserInteractionEnabled = false
titleLabel?.font = RobotoFont.regular
isOpaque = true
}
}
并创建此按钮:
let button = ChipButton()
button.title = "default chip"
view.layout(button).height(32).center(offsetY: -150)
接触芯片/图标芯片
import UIKit
import Material
class ChipIconButton: ChipButton {
/*override func prepare() {
super.prepare()
contentEdgeInsets = EdgeInsets(top: 0, left: 16, bottom: 0, right: 12)
}*/
public convenience init(image: UIImage?, title: String?){
self.init()
prepare(with: image, title: title)
}
private func prepare(with image: UIImage?, title: String?) {
self.image = image
self.title = title
self.imageView?.backgroundColor = UIColor.darkGray // this works
self.imageView?.cornerRadiusPreset = .cornerRadius4 // this works
self.imageView?.tintColor = Color.black // this doesn't work
self.imageEdgeInsets = EdgeInsets(top: 0, left: -8, bottom: 0, right: 12)
self.titleEdgeInsets = EdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
self.contentEdgeInsets = EdgeInsets(top: 0, left: 8, bottom: 0, right: 12)
}
}
我想来
-
将 UIImageView 调整为芯片的高度(即 32 点)
I tried with self.imageView?.frame = CGRect(x: 50, y: 50, width: 32, height: 32) but nothing changed 将 UIImage 调整为小一点(到 20 磅)
-
改变 UIImage 的 tintColor
I tryed with self.imageView?.tintColor = Color.black but nothing changed
可删除的芯片
import UIKit
import Material
class ChipDeleteableButton: ChipButton {
override func prepare() {
super.prepare()
self.image = #imageLiteral(resourceName: "ic_close_white_24px")
self.title = title
//self.frame = CGRect(x: 50, y: 50, width: 32, height: 32)
self.imageView?.backgroundColor = UIColor.darkGray
self.imageView?.cornerRadiusPreset = .cornerRadius4
self.imageView?.tintColor = Color.black
self.imageEdgeInsets = EdgeInsets(top: 0, left: self.frame.size.width, bottom: 0, right: 0)
self.titleEdgeInsets = EdgeInsets(top: 0, left: 0, bottom: 0, right: self.frame.size.width)
self.contentEdgeInsets = EdgeInsets(top: 0, left: 8, bottom: 0, right: 12)
}
}
在这里我尝试使用 imageEdgeInsets 和 titleEdgeInsets 切换标签的位置,但 self.frame.size.width 返回的宽度不正确(可能是 AutoLayout 的原因,但我不确定)
帮助
希望有人可以帮助我!
ps。我是 swift/xcode 的新手
【问题讨论】:
-
我找到了解决方法: > 3. 为任何按钮类型(.system-button 除外)更改 UIImage 的 tintColor,必须将 .withRenderingMode(.alwaysTemplate) 添加到 img。例如:self.image = UIImage(named: "image-name").withRenderingMode(.alwaysTemplate)
-
UIImage(named: "image-name")?.withRenderingMode(.alwaysTemplate) 问号很重要
标签: ios swift material-design cosmicmind