IOS Apps 开发(Swift)(6)——Implement a Custom Control(2)
来源:互联网 发布:cmd打开端口命令 编辑:程序博客网 时间:2024/05/24 15:40
前言:网上一直没有找到用Swift开发IOS的好的教程,所以找了官网的文档翻译一下算了。如有错误欢迎指正。博主首发CSDN,mcf171专栏。
博客链接:mcf171的博客
原文链接:Implement a Custom Control
——————————————————————————————
在上一节文章中我们已经将资源添加到了我们的项目工程中,在这一节我们将让按钮显示这些图片
给按钮设置星星图片
1、打开RatingControl.swift
2、在 init?(coder:)初始化器中的for-in 循环前增加以下两行代码
let filledStarImage = UIImage(named: "filledStar")let emptyStarImage = UIImage(named: "emptyStar")
3、在for-in 循环的按钮初始化之后增加下列代码
button.setImage(emptyStarImage, forState: .Normal)button.setImage(filledStarImage, forState: .Selected)button.setImage(filledStarImage, forState: [.Highlighted, .Selected])
上述代码为按钮的不同状态设置了不同的图片。当按钮没有出现的时候,显示的是空心星星,当选中的时候时候出现的是实心的星星。
4、删除颜色代码
button.backgroundColor = UIColor.redColor()
因为我们已经有了图片了,所以我们移除掉颜色代码
5、增加下述代码
button.adjustsImageWhenHighlighted = false
上述代码保证了当按钮状态改变的时候不显示一个额外的高亮效果
最终的初始化器代码为
required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) let emptyStarImage = UIImage(named: "emptyStar") let filledStarImage = UIImage(named: "filledStar") for _ in 0..<5 { let button = UIButton() button.setImage(emptyStarImage, forState: .Normal) button.setImage(filledStarImage, forState: .Selected) button.setImage(filledStarImage, forState: [.Highlighted, .Selected]) button.adjustsImageWhenHighlighted = false button.addTarget(self, action: "ratingButtonTapped:", forControlEvents: .TouchDown) ratingButtons += [button] addSubview(button) }}
里程碑:运行app。我们将看到现在是星星图案而不是红色的按钮,点击任何一个按钮都会在控制台显示消息,但是按钮并没有切换图片
实现按钮行为
用户需要通过点击星星来进行打分,所以我们需要替换之前在ratingButtonTapped中写的代码
实现打分新闻
1、在RatingControl.swift中找到ratingButtonTapped方法func ratingButtonTapped(button: UIButton) { print("Button pressed
0 0
- IOS Apps 开发(Swift)(6)——Implement a Custom Control(2)
- IOS Apps 开发(Swift)(6)——Implement a Custom Control(1)
- iOS Apps 开发(Swift)(9)——Implement Navigation
- iOS Apps 开发(Swift)(10)——Implement Edit and Delete Behavior
- IOS Apps 开发(Swift)(3)——Build a Basic UI(2)
- IOS Apps 开发(Swift)(3)——Build a Basic UI(1)
- IOS Apps 开发(Swift)(8)——Create a Table View
- IOS Apps 开发(Swift)(2)——Learn the Essentials of Swift(2)
- IOS Apps 开发(Swift)(2)——Learn the Essentials of Swift(1)
- iOS Apps 开发(Swift)(11)——Persist Data
- ios开发(十六)custom control
- IOS Apps 开发(Swift)(4)——Connect the UI to Code(2)
- IOS Apps 开发(Swift)(4)——Connect the UI to Code(1)
- IOS Apps 开发(Swift)(1)——Jump Right In
- IOS Apps 开发(Swift)(5)——Work with View Controllers
- IOS Apps 开发(Swift)(7)——Define Your Data Model
- iOS开发(Swift)——代理
- iOS开发Swift篇—(八)函数(2)
- PHP反射(ReflectionClass、ReflectionMethod)在ThinkPHP框架的控制器调度模块中的应用
- Android studio 中 butterknife zelezny 的使用
- android app Lose Weight
- linux sudo 命令学习笔记
- UVA 1648(p346)----Business Center
- IOS Apps 开发(Swift)(6)——Implement a Custom Control(2)
- linux设备驱动归纳总结(八):1.总线、设备和驱动
- file not found. nginx php nginx 如何开启解析 PHP 的功能
- Git分支管理总结
- SQL Server数据库设计规范
- linux设备驱动归纳总结(八):2.总线、设备和驱动的关系
- 通过 ip 直接访问项目
- java日志,需要知道的几件事(commons-logging,log4j,slf4j,logback)
- ubuntu安装依赖包