iOS自定义控件一
发布日期:2022-03-18 08:27:40 浏览次数:19 分类:技术文章

本文共 4975 字,大约阅读时间需要 16 分钟。

文章内容来自学习系列课程

第一个自定义控件

这个自定义控件是一个简单的自定义View,左边是一个UIImageView,右边是一个LabelIconControl的代码如下,包括设置约束:

class IconControl: UIView {    private lazy var imageView: UIImageView = {        let iv = UIImageView()        iv.translatesAutoresizingMaskIntoConstraints = false        return iv    }()    private var label: UILabel = {        let label = UILabel()        label.translatesAutoresizingMaskIntoConstraints = false        label.font = UIFont.systemFontOfSize(30.0, weight: UIFontWeightLight)        return label    }()    private  var spacingConstraint: NSLayoutConstraint!    var spacing: CGFloat = 20.0 {        didSet{            spacingConstraint!.constant = spacing        }    }    override init(frame: CGRect) {        super.init(frame: frame)        sharedInitalizaiton()    }    required init?(coder aDecoder: NSCoder) {        super.init(coder: aDecoder)        sharedInitalizaiton()    }}extension IconControl {    var image: UIImage? {        get {            return imageView.image        }        set(newImage) {            imageView.image = newImage?.imageWithRenderingMode(.AlwaysTemplate)        }    }    var text: String? {        get {            return label.text        }        set(newText) {            label.text = newText        }    }}extension IconControl {    private func sharedInitalizaiton() {        translatesAutoresizingMaskIntoConstraints = false        addSubview(label)        addSubview(imageView)        //创建约束 间隔        spacingConstraint = label.leftAnchor.constraintEqualToAnchor(imageView.rightAnchor, constant: spacing)        NSLayoutConstraint.activateConstraints([            imageView.leadingAnchor.constraintEqualToAnchor(layoutMarginsGuide.leadingAnchor),            imageView.topAnchor.constraintEqualToAnchor(layoutMarginsGuide.topAnchor),            imageView.bottomAnchor.constraintEqualToAnchor(layoutMarginsGuide.bottomAnchor),            spacingConstraint,            label.rightAnchor.constraintEqualToAnchor(layoutMarginsGuide.rightAnchor),            imageView.centerYAnchor.constraintEqualToAnchor(label.centerYAnchor)            ])        //设置如何压缩和拉伸        label.setContentHuggingPriority(UILayoutPriorityDefaultHigh, forAxis: .Horizontal)        imageView.setContentHuggingPriority(UILayoutPriorityDefaultHigh, forAxis: .Horizontal)        setContentHuggingPriority(UILayoutPriorityDefaultHigh, forAxis: .Horizontal)        layer.cornerRadius = 10    }}

在ViewController上添加view,并设置约束:

lazy var iconControl: IconControl = {  return IconControl(frame: .zero)}()---iconControl.text = "My Icon Controld"iconControl.image = UIImage(named: "cocktail")iconControl.spacing = 50.0iconControl.backgroundColor = UIColor(white: 0.9, alpha: 1.0)view.addSubview(iconControl)NSLayoutConstraint.activateConstraints([    iconControl.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor),    iconControl.centerYAnchor.constraintEqualToAnchor(view.centerYAnchor)    ])

效果如下:

效果

与Interface Builder整合

自定义控件与Interface Builder整合

  • 在class上添加@IBDesignable
  • 在需要的property上添加@IBInspectable

这样就可以通过在Interface Builder中设置对应的属性值

Interaction和UIControl

在Cocoa Touch中公有5中interaction方式

  • Target-Action 用于UIControl、UIView的子类
  • Delegation代理
  • Command Pattern,例如传递闭包
  • Notification
  • Key-Value Observation

最简单是Target-Action

public class UIControl : UIView {    //...    public func addTarget(target: AnyObject?, action: Selector,    forControlEvents controlEvents: UIControlEvents)    public func removeTarget(target: AnyObject?, action: Selector,    forControlEvents controlEvents: UIControlEvents)    //...    public func sendAction(action: Selector, to target: AnyObject?,    forEvent event: UIEvent?)    public func sendActionsForControlEvents(controlEvents: UIControlEvents)}

所以要让IconControl可以交互,可以让IconControl继承自UIControl,而不是UIView。这样就可以像按钮一样给它添加事件:

添加事件

同样可以给IconControl添加UITapGestureRecognizer,并触发.TouchUpInside对应的Action方法。

如何实现Button一样的效果,在点击时IconControl有外观上的变化?
在本例中,使用的是重写touchesBegan等一系列方法,并改变tintAdjustmentMode,然后重写tintColorDidChange方法,做出对应的改变

extension IconControl {  override func tintColorDidChange() {    super.tintColorDidChange()    label.textColor = tintColor  }}extension IconControl {  private func addTapGestureRecognizer() {    let tapGestureRecogniser = UITapGestureRecognizer(target: self, action: "handleIconTapped:")    addGestureRecognizer(tapGestureRecogniser)  }  func handleIconTapped(sender: UITapGestureRecognizer) {    sendActionsForControlEvents(.TouchUpInside)  }  override func touchesBegan(touches: Set
, withEvent event: UIEvent?) { animateTintAdjustmentMode(.Dimmed) } override func touchesCancelled(touches: Set
?, withEvent event: UIEvent?) { animateTintAdjustmentMode(.Normal) } override func touchesEnded(touches: Set
, withEvent event: UIEvent?) { animateTintAdjustmentMode(.Normal) } private func animateTintAdjustmentMode(mode: UIViewTintAdjustmentMode) { UIView.animateWithDuration(mode == .Normal ? 0.3 : 0.05) { self.tintAdjustmentMode = mode } }}

点击效果如下:

点击效果

转载地址:https://windzen.blog.csdn.net/article/details/53407049 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Swift-泛型
下一篇:CALayer相关文章

发表评论

最新留言

感谢大佬
[***.8.128.20]2023年05月25日 04时17分37秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

最新文章

签到模块反思 2019-12-22 11:35:40
程序规范 2019-12-22 11:35:40
任务模块反思 2019-12-22 11:35:41
小心得 2019-12-22 11:35:41
下Java 调用cmd.exe命令 2019-12-22 11:35:41
Apache+Tomcat+Proxy集群要点 2019-12-22 11:35:41
堆排序学习 2019-12-22 11:35:41
Design Pattern - Adapter 2019-12-22 11:35:39
Java动态代理 2019-12-22 11:35:39
【转】Design for performance - Interfaces matter 2019-12-22 11:35:39
【转】Design for performance - Remote interfaces 2019-12-22 11:35:39
【转】Design for performance - Reduce object creation 2019-12-22 11:35:40
页面用js脚本控制文本框里输入的类型 2019-12-22 11:35:40
关于字符串的空格问题——去掉左空格、右空格、中间的空格、前后的空格 2019-12-22 11:35:40
Eclipse Apache Axis2集成 2019-12-22 11:35:38
RMI 起步 2019-12-22 11:35:38
EJB和RMI 2019-12-22 11:35:38
EAI技术和概念解析 2019-12-22 11:35:38
URL和URI的区别 2019-12-22 11:35:38
Design Pattern - Decorator 2019-12-22 11:35:39