Swift - UIButton

本文详细介绍了如何在Swift UI中自定义按钮样式,包括位置、文字、颜色、字体、背景、图片及触摸事件设置,并展示了如何为按钮设置动态图片,实现更丰富的交互效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

mport UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //创建Button类型:system,custom,contactAdd,(detailDisclosure,infoDark,infoLight效果一样),roundedRect
        let button = UIButton(type: .custom)
        //设置Button位置
      button.frame = CGRect(x: 150, y: 250, width: 100, height: 100)
        //设置按钮文字
        button.setTitle("按钮", for: .highlighted)//有三种状态:普通状态:normal,触摸状态:hightlighted禁用状态:disabled
        //设置按钮文字
        button.setTitleColor(UIColor.black, for: .normal)//有三种状态
        //设置按钮文字阴影
        button.setTitleShadowColor(UIColor.gray, for: .normal)
        //设置按钮字体和大小
        button.titleLabel?.font = UIFont.systemFont(ofSize:11)//系统字体
        button.titleLabel?.font = UIFont(name: "Farah", size: 11)//自定义字体
        //设置按钮背景颜色
        button.backgroundColor = UIColor.orange
        //设置按图案(如果自定义图标就不需要设置Button类型)
        button.setImage(UIImage(named:"icon"), for: .normal)
        //设置button的图片在高亮,禁用状态下图标是否透明
        button.adjustsImageWhenHighlighted = false
        button.adjustsImageWhenDisabled = false
        //保留图案本色(当Button类型为custom时无需次代码)
        let image = UIImage(named: "icon")?.withRenderingMode(.alwaysOriginal)
        button.setImage(image, for: .normal)
        //设置按钮背景图片
        button.setBackgroundImage(UIImage(named: "Image"), for: .normal)
        //按钮文字过长处理方法
        button.titleLabel?.lineBreakMode = .byClipping//其他处理方法详情请看Label章节
        //按钮触摸点击事件
        button.addTarget(self, action: #selector(ViewController.TapButton), for: .touchUpInside)
//        touchDown:单点触摸按下事件,点触屏幕
//        touchDownRepeat:多点触摸按下事件
//        touchDragInside:触摸在控件内拖动时
//        touchDragOutside:触摸在控件外拖动时
//        touchDragEnter:触摸从控件之外拖动到内部时
//        touchDragExit:触摸从控件内部拖动到外部时
//        touchUpInside:在控件之内触摸并抬起事件
//        touchUpOutside:在控件之外触摸抬起事件
//        touchCancel:触摸取消事件,即一次触摸因为放上太多手指而被取消,或者电话打断
        
        //添加Button到视图中
        self.view.addSubview(button)

    }
    @objc func TapButton()
    {
        print("你点击了此按钮")
    }
    
}

Button设置动态图片

import UIKit
class ViewController: UIViewController,UITextFieldDelegate{
    override func viewDidLoad() {
        super.viewDidLoad()
        //图片命名为animation0,animation1,animation2
        let image = UIImage.animatedImageNamed("animation", duration: 2.0)
        let button = UIButton(frame: CGRect(x: 150, y: 250, width: 100, height: 100))
        button.setImage(image, for: .normal)
        self.view.addSubview(button)
    }
    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值