继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

CoreText(五)-自定义光标

慕虎7371278
关注TA
已关注
手记 1125
粉丝 201
获赞 871

在阅读电子书的时候,可能有一个功能是长按一段文字,并出现自定义的光标。

效果图

webp

WX20181220-171219@2x.png

具体代码如下:

class CustomCursorView: UIView {// 圈圈在下边private var circleOnBottom: Bool = false// 光标颜色var cursorColor: UIColor = .red {
    didSet {
        setNeedsDisplay()
    }
}

init(frame: CGRect, circleOnBottom: Bool) {    super.init(frame: frame)    
    self.circleOnBottom = circleOnBottom
    backgroundColor = UIColor.clear
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}


override func draw(_ rect: CGRect) {

    let context = UIGraphicsGetCurrentContext()
    cursorColor.set()

    let cursorWidth = bounds.width / 2
 
    context?.addRect(CGRect(x: cursorWidth * 0.5, y: circleOnBottom ? 0 : 1, width: cursorWidth, height: bounds.height - 1))
    context?.fillPath()    if circleOnBottom {
        context?.addEllipse(in: CGRect(x: 0, y: bounds.height - bounds.width, width: bounds.width, height: bounds.width))
    } else {
        context?.addEllipse(in: CGRect(x: 0, y: 0, width: bounds.width, height: bounds.width))
    }

    context?.fillPath()
    cursorColor.set()
}

}

使用方法:

  let leftCursor = CustomCursorView(frame: CGRect(x: 100, y: 100, width: 8, height: 30), circleOnBottom: false)
  view.addSubview(leftCursor)    
  let rightCursor = CustomCursorView(frame: CGRect(x: 200, y: 100, width: 8, height: 30), circleOnBottom: true)
  view.addSubview(rightCursor)



作者:三_木子_
链接:https://www.jianshu.com/p/7e090b12982a


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP