首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >iOS - UIButton系统选择的图像

iOS - UIButton系统选择的图像
EN

Stack Overflow用户
提问于 2017-10-12 18:53:08
回答 1查看 520关注 0票数 0

我有一个带有选择切换的透明图像的UIButton。在当前配置中,我使用的是系统按钮类型,因为它可以很好地颠倒按钮。然而,通过这种反转,我得到了一个带有边框的图像,并且我希望这个图像填充整个按钮。如何才能做到这一点?我想从系统中保留透明的遮罩。

Here is the repository.

下图中显示的是选定的系统状态。

EN

回答 1

Stack Overflow用户

发布于 2017-10-12 20:17:42

创建UIButton的子类并覆盖isSelected

例如

代码语言:javascript
运行
复制
  class CustomButton: UIButton {

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */




    override var isSelected: Bool {


        didSet {
            if isSelected {
                self.backgroundColor = UIColor.blue
                self.tintColor = UIColor.white
            } else {
                self.backgroundColor = .white
                self.tintColor = UIColor.red
            }

        }
    }

}

根据需要更改颜色

在视图控制器中,如下所示

代码语言:javascript
运行
复制
class ViewController: UIViewController {

@IBOutlet weak var button: CustomButton!
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    button.isSelected = false
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
@IBAction func btnTapped(_ sender: Any) {
    button.isSelected = !button.isSelected
}

}

还有一件事你必须将图像的渲染选项设置为模板

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46707788

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档