分享好友 编程语言首页 频道列表

[Swift]最强UIButton解析 | #selector()绑定点击事件

Swift文章/教程  2023-02-09 05:520

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/ 
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10869372.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

函数参数既可以具有名称(在函数体内使用),也可以具有参数标签(在调用函数时使用)。

如函数参数标签和参数名称中所述。方法参数也是如此,因为方法只是与类型相关联的函数。

  1 //
  2 //  ViewController.swift
  3 //  demo
  4 //
  5 //  Created by qiang zeng on 2020/2/20.
  6 //  Copyright © 2020 strengthen All rights reserved.
  7 //
  8 
  9 import UIKit
 10 
 11 class ViewController: UIViewController {
 12     override func viewDidLoad() {
 13         super.viewDidLoad()
 14         //初始化一个按钮
 15         let button:UIButton = getButton()
 16         //将按钮添加到视图中
 17         self.view.addSubview(button)
 18         
 19         //设置按钮的点击事件:button.addTarget(Any?, action: Selector, for: UIControlEvents)
 20         //1、touchDown:单点触摸按下事件,点触屏幕
 21         //2、touchDownRepeat:多点触摸按下事件,点触计数大于1,按下第2、3或第4根手指的时候
 22         //3、touchDragInside:触摸在控件内拖动时
 23         //4、touchDragOutside:触摸在控件外拖动时
 24         //5、touchDragEnter:触摸从控件之外拖动到内部时
 25         //6、touchDragExit:触摸从控件内部拖动到外部时
 26         //7、touchUpInside:在控件之内触摸并抬起事件
 27         //8、touchUpOutside:在控件之外触摸抬起事件
 28         //9、touchCancel:触摸取消事件,即一次触摸因为放上太多手指而被取消,或者电话打断
 29         
 30         //按钮绑定点击事件,无参数传递方式1
 31         button.addTarget(self, action: #selector(buttonClick1), for: .touchUpInside)
 32         button.addTarget(self, action: #selector(buttonClick2), for: .touchUpInside)
 33         button.addTarget(self, action: #selector(buttonClick3), for: .touchUpInside)
 34         //按钮绑定点击事件,无参数传递方式2
 35         //Swift提倡用方式2
 36         button.addTarget(self, action: #selector(ViewController.buttonClick1), for: .touchUpInside)
 37         button.addTarget(self, action: #selector(ViewController.buttonClick2), for: .touchUpInside)
 38         button.addTarget(self, action: #selector(ViewController.buttonClick3), for: .touchUpInside)
 39         
 40         //按钮绑定点击事件,带button参数传递
 41         //与点击方法的参数相同,无参数标签使用参数名称,传递点击的按钮
 42         button.addTarget(self, action: #selector(buttonClick2(button:)), for: .touchUpInside)
 43         
 44         //与点击方法的参数相同,有参数标签使用参数标签
 45         button.addTarget(self, action: #selector(buttonClick3(_ :)), for: .touchUpInside)
 46     }
 47     
 48     //MARK:按钮点击1
 49     @objc func buttonClick1()
 50     {
 51         //TODO
 52     }
 53     
 54     //MARK:按钮点击2
 55     @objc func buttonClick2(button:UIButton)
 56     {
 57         //TODO
 58     }
 59     
 60     //MARK:按钮点击3
 61     @objc func buttonClick3(_ button:UIButton)
 62     {
 63         //TODO
 64     }
 65     
 66     //MARK:获取按钮
 67     func getButton() -> UIButton
 68     {
 69         //1、UIButtonType.system:前面不带图标,默认文字颜色为蓝色,有触摸时的高亮效果
 70         //2、UIButtonType.custom:定制按钮,前面不带图标,默认文字颜色为白色,无触摸时的高亮效果
 71         //3、UIButtonType.contactAdd:前面带“+”图标按钮,默认文字颜色为蓝色,有触摸时的高亮效果
 72         //4、UIButtonType.detailDisclosure:前面带“!”图标按钮,默认文字颜色为蓝色,有触摸时的高亮效果
 73         //5、UIButtonType.infoDark:为感叹号“!”圆形按钮
 74         //6、UIButtonType.infoLight:为感叹号“!”圆形按钮
 75         let button:UIButton = UIButton(type:.custom)
 76         
 77         //设置按钮的坐标和显示区域
 78         button.frame = CGRect(x:50, y:50, width:50,height: 50)
 79         //设置按钮的背景颜色
 80         button.backgroundColor = UIColor.red
 81         //设置按钮背景图片:button.setBackgroundImage(UIImage?, for: UIControlState)
 82         button.setBackgroundImage(UIImage(named:"bg"), for: .normal)
 83         //设置按钮字体和大小
 84         button.titleLabel?.font = UIFont.init(name:"Arial",size:16)
 85         //设置字体大小
 86         button.titleLabel?.font = UIFont.systemFont(ofSize: 22)
 87         //Tag
 88         button.tag = 1
 89         //高亮状态
 90         button.isHighlighted = true
 91         //设置镂空图片的颜色
 92         button.tintColor = UIColor.white
 93         //设置圆角
 94         button.layer.masksToBounds = true
 95         //圆角半径
 96         button.layer.cornerRadius = 10
 97         //边框粗细
 98         button.layer.borderWidth = 0.5
 99         //设置边框
100         button.layer.borderColor = UIColor.black.cgColor
101         
102         //设置按钮不同状态下的文字、颜色和阴影颜色
103         //1、UIControlState.normal//普通状态
104         //2、UIControlState.highlighted//触摸状态
105         //3、UIControlState.disabled//禁用状态
106         //设置各个状态的文字内容
107         button.setTitle("普通状态", for: .normal)
108         button.setTitle("触摸状态", for: .highlighted)
109         button.setTitle("禁用状态", for: .disabled)
110         //设置各个状态下文字阴影的颜色
111         button.setTitleShadowColor(UIColor.green, for:.normal)
112         button.setTitleShadowColor(UIColor.yellow, for:.highlighted)
113         button.setTitleShadowColor(UIColor.gray, for:.disabled)
114 
115         //设置按钮图标:button.setImage(UIImage?, for: UIControlState)
116         //当按钮类型为custom,处于highlighted和disable状态下图标会变暗,
117         //可以通过设置来禁用这种情况
118         button.setImage(UIImage(named:"img"), for: .normal)
119         button.adjustsImageWhenHighlighted = false //使触摸模式下按钮也不会变暗
120         button.adjustsImageWhenDisabled = false //使禁用模式下按钮也不会变暗
121         
122         //按钮文字太长处理方式:titleLabel 的 lineBreakMode 属性
123         //byTruncatingHead:省略头部文字,省略部分用...代替
124         //byTruncatingMiddle:省略中间部分文字,省略部分用...代替(默认)
125         //byTruncatingTail:省略尾部文字,省略部分用...代替
126         //byClipping:直接将多余的部分截断
127         //byWordWrapping:自动换行(按词拆分)
128         //byCharWrapping:自动换行(按字符拆分)
129         //注意:当设置自动换行后(byWordWrapping 或 byCharWrapping),我们可以在设置 title 时通过 \n 进行手动换行。
130         button.titleLabel?.lineBreakMode = .byWordWrapping
131 
132         //调整文字和图标之间的间距:通过图片偏移量(imageEdgeInsets)设置间距
133         button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -10, bottom: 0, right: 0)
134         //通过文字偏移量(titleEdgeInsets)设置间距
135         button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)
136         //调换或调整文字和图片位置:通过设置 titleEdgeInsets 和 imageEdgeInsets 即可实现。
137         let imageSize = button.imageRect(forContentRect: button.frame)//获取图标的CGRect
138         let titleFont = button.titleLabel?.font//获取字体
139         let titleSize = button.currentTitle!.size(withAttributes:[NSAttributedString.Key.font: titleFont!])//获取文字的尺寸
140         button.titleEdgeInsets = UIEdgeInsets(top: 0, left: -(imageSize.width * 2) , bottom: 0, right: 0)
141         button.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -(titleSize.width * 2 + 10))
142         
143         //扩展方法示例:快速的设置图片和文字的相对位置,以及间距
144         button.set(icon: UIImage(named:"img"), title: "标题", titleLocation: .top, padding: 10, state: .normal)
145         return button
146     }
147 }
148 
149 //MARK:
150 extension UIButton{
151     func set(icon image: UIImage?, title: String, titleLocation: UIView.ContentMode, padding: CGFloat, state: UIControl.State ) {
152         self.imageView?.contentMode = .center
153         self.setImage(image, for: state)
154         relativeLocation(title: title, location: titleLocation, padding: padding)
155         self.titleLabel?.contentMode = .center
156         self.setTitle(title, for: state)
157     }
158     
159     private func relativeLocation(title: String, location: UIView.ContentMode, padding: CGFloat){
160         let imageSize = self.imageRect(forContentRect: self.frame)
161         let titleFont = self.titleLabel?.font!
162         let titleSize = title.size(withAttributes: [NSAttributedString.Key.font : titleFont!])
163         
164         var titleInsets: UIEdgeInsets
165         var imageInsets: UIEdgeInsets
166         
167         switch location {
168         case .top:
169             titleInsets = UIEdgeInsets(top: -(imageSize.height + titleSize.height + padding),
170                                        left: -(imageSize.width), bottom: 0, right: 0)
171             imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -titleSize.width)
172         case .left:
173             titleInsets = UIEdgeInsets(top: 0, left: -(imageSize.width * 2), bottom: 0, right: 0)
174             imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -(titleSize.width * 2 + padding))
175         case .bottom:
176             titleInsets = UIEdgeInsets(top: (imageSize.height + titleSize.height + padding),
177                                        left: -(imageSize.width), bottom: 0, right: 0)
178             imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -titleSize.width)
179         case .right:
180             titleInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -padding)
181             imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
182         default:
183             titleInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
184             imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
185         }
186         self.titleEdgeInsets = titleInsets
187         self.imageEdgeInsets = imageInsets
188     }
189 }

 

查看更多关于【Swift文章/教程】的文章

展开全文
相关推荐
反对 0
举报 0
评论 0
图文资讯
热门推荐
优选好物
更多热点专题
更多推荐文章
swift 命令行工具初探
亲爱的同学们好,今天我们要介绍这么一个东西。相信有过解释型语言(PHP,Ruby,等)使用经验的同学会更加熟悉,就是 Swift 也为我们提供了命令行运行工具,俗称 REPL。好了,我们进入正题,在安装好 Swift 开发环境的机器上,打开命令行,输入 swift 命令,就进

0评论2023-03-16457

swift -懒加载创建view
 // 只有外界访问到headerView的时候才会去执行闭包, 然后将闭包的返回值赋值给headerView    // 注意: 一定要记住闭包后面需要写上(), 代表执行闭包    //懒加载创建UIView    lazy var headerView: UIView = {        let view = UIView()

0评论2023-02-09837

Swift--非常好用的适合局部的代码约束
// 哪个控件的哪个属性等于(大于、小于)另外一个控件的哪个属性乘以多少再加上多少 eg:let widthContraint = NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLa

0评论2023-02-09722

Swift -- 官方文档Swift-Guides的学习笔记
在经历的一段时间的郁闷之后,我发现感情都是虚伪的,只有代码是真实的(呸)因为看了swift语法之后依然不会用swift,然后我非常作死的跑去看官方文档,就是xcode里自带的help》documentation and API reference其中的swift里的guide这里主要总结一下里面每一

0评论2023-02-09486

Swift - 进度条(UIProgressView)的用法
 1,创建进度条1234var progressView=UIProgressView(progressViewStyle:UIProgressViewStyle.Default)progressView.center=self.view.centerprogressView.progress=0.5 //默认进度50%self.view.addSubview(progressView); 2,设置进度,同时有动画效果1p

0评论2023-02-09398

[Swift]LeetCode358. 按距离为k隔离重排字符串 $ Rearrange String k Distance Apart
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)➤GitHub地址:https://github.com/strengthen/LeetCode➤原文

0评论2023-02-09394

swift 实现QQ好友列表功能
最近项目中有类似QQ好友列表功能,整理了一下,话不多说,直接上代码import UIKitclass QQFriend: NSObject {var name: String?var intro: String?init(dic: NSDictionary) {super.init()self.setValuesForKeys(dic as! [String : AnyObject])}}import UIKitc

0评论2023-02-09810

Swift - 界面的跳转模式
 iOS开发中界面跳转有两种方式,上下跳转和左右跳转。上下跳转_TO: let secondViewController = SecondViewController()  self.presentViewController(secondViewController, animated: true, completion: nil)   上下跳转_BACK:dismissViewC

0评论2023-02-09965

【Swift】Starscream 实现socket连接
import UIKitimport Starscreamclass ViewController: UIViewController,WebSocketDelegate {var socket: WebSocket!var isConnected = falselet server = WebSocketServer()var button1 : UIButton!var button2 : UIButton!override func viewDidLoad() {sup

0评论2023-02-09861

swift 添加rootViewController
   let rootV = ViewController()       let  rootNav  = UINavigationController.init(rootViewController: rootV)       self.window?.rootViewController=rootNav

0评论2023-02-09473

iOS8 蓝牙设备的重连接(retrieve) Swift实现
  今天App写到了蓝牙重连的阶段,以前针对sdk 6.0写的代码,蓝牙设备的回复是通过- (void)retrievePeripherals:(NSArray *)peripheralUUIDs然后回调 centralManager:didRetrievePeripherals:函数来得到可以回复设备的Array。在SDK7之后,- (void)retrievePe

0评论2023-02-09891

Swift - enumerateObjectsUsingBlock的用法
enumerateobjectsusingblock:不是Array的方法在NSArray使用。如果你想使用它,你需要一个实例NSArray而不是Array。import Foundationvar array: NSArray = ["Some", "strings", "in", "an", "array"]array.enumerateObjectsUsingBlock({ object, index

0评论2023-02-09442

Swift数组的加法运算符用法:array1 += array2
var stringList1 = [String]()//创建String类型空数组var stringList2 = ["1", "3", "5", "7", "zoo", "9","zoo"]var stringList3 :[String] = ["2", "4", "6","apple&q

0评论2023-02-09881

更多推荐