使用UILabel上的捏合手势调整字体和标签框架的大小?

时间:2019-01-16 08:40:27

标签: ios swift uilabel pinchzoom uipinchgesturerecognizer

每当用户使用捏手势调整标签大小时,即可平滑地增大或减小字体大小。

注意

  • 在不影响字体质量的情况下
  • 不仅改变了UILabel的规模
  • 支持多行文字
  • 旋转手势应与捏手势配合使用
  • 参考:SnapChat或Instagram文本编辑器工具

extension String {
    func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
        let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: UIFont(name: font.fontName, size: font.pointSize)!], context: nil)
        return ceil(boundingBox.height)
    }

    func width(withConstrainedHeight height: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
        let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: UIFont(name: font.fontName, size: font.pointSize)!], context: nil)
        return ceil(boundingBox.width)
    }
}

func resizeLabelToText(textLabel : UILabel)
{
    let labelFont = textLabel.font
    let labelString = textLabel.text
    let labelWidth : CGFloat = labelString!.width(withConstrainedHeight: textLabel.frame.size.height, font: labelFont!)
    let labelHeight : CGFloat = labelString!.height(withConstrainedWidth: labelWidth, font: labelFont!)

    textLabel.frame = CGRect(x: textLabel.frame.origin.x, y: textLabel.frame.origin.y, width: labelWidth, height: labelHeight)
    textLabel.font = labelFont
}

func pinchedRecognize(_ pinchGesture: UIPinchGestureRecognizer) {
    guard pinchGesture.view != nil else {return}

    if (pinchGesture.view is UILabel) {
        let selectedTextLabel = pinchGesture.view as! UILabel

        if pinchGesture.state == .began || pinchGesture.state == .changed {
            let pinchScale = round(pinchGesture.scale * 1000) / 1000.0
            if (pinchScale < 1) {
                selectedTextLabel.font = selectedTextLabel.font.withSize(selectedTextLabel.font.pointSize - pinchScale)
            }
            else {
                selectedTextLabel.font = selectedTextLabel.font.withSize(selectedTextLabel.font.pointSize + pinchScale)
            }
            resizeLabelToText(textLabel: selectedTextLabel)
        }
    }
}

3 个答案:

答案 0 :(得分:1)

我用以下代码解决了问题,该代码可以很好地处理所提及的各个方面,类似于Snapchat和Instagram:

textview.contentInset = UIEdgeInsets(top: 2, left: 10, bottom: 2, right: 10)

答案 1 :(得分:0)

每次UILabel大小更改后,调用以下方法。

{"name":NULL,"account":NULL,"status":NULL}

答案 2 :(得分:0)

您可以尝试:

1-设置此标签的最大字体大小

2-将换行符设置为“截尾”

3-将自动收缩设置为最小字体大小(最小大小)

enter image description here