gpt4 book ai didi

swift - 使用选择矩形(:) with UITextField subclass

转载 作者:行者123 更新时间:2023-11-30 10:35:33 26 4
gpt4 key购买 nike

我有一个 UITextField 子类,我在其中覆盖左 View 、文本和插入符号的绘图矩形。这是使用 leftViewRect(forBounds:)leftViewRect(forBounds:)caretRect(for:) 等完成的。一切都按预期工作。

问题是,因为我在 caretRect(for:) 中将绘图矩形(向上)移动 -2 点,所以所选文本的绘图矩形比应有的位置低 2 点。我尝试重写 selectionRects(for:),但 UITextSelectionRectrect 是仅获取属性。实现这一目标的正确方法是什么?

代码

public override func selectionRects(for range: UITextRange) -> [UITextSelectionRect] {
super.selectionRects(for: range).map {
var selectionRect = $0
selectionRect.rect.origin.y -= 2 // Left side of mutating operator isn't mutable: 'rect' is a get-only property
return selectionRect
}
}

最佳答案

根据 rmaddy 的评论和 this answer ,我通过子类化 UITextSelectionRect 并使用修改后的 rect 传入来自 super.selectionRects(for: range) 的映射值来解决这个问题。这就是我的结论:

public final class MyUITextField: UITextField {
public override func selectionRects(for range: UITextRange) -> [UITextSelectionRect] {
super.selectionRects(for: range).map {
MyTextSelectionRect(
rect: CGRect(x: $0.rect.origin.x, y: $0.rect.origin.y - 2, width: $0.rect.width, height: $0.rect.height),
writingDirection: $0.writingDirection,
containsStart: $0.containsStart,
containsEnd: $0.containsEnd,
isVertical: $0.isVertical
)
}
}

//...
}
public final class MyTextSelectionRect: UITextSelectionRect {
public override var rect: CGRect { _rect }
public override var writingDirection: NSWritingDirection { _writingDirection }
public override var containsStart: Bool { _containsStart }
public override var containsEnd: Bool { _containsEnd }
public override var isVertical: Bool { _isVertical }

private let _rect: CGRect
private let _writingDirection: NSWritingDirection
private let _containsStart: Bool
private let _containsEnd: Bool
private let _isVertical: Bool

public init(
rect: CGRect,
writingDirection: NSWritingDirection,
containsStart: Bool,
containsEnd: Bool,
isVertical: Bool
) {
_rect = rect
_writingDirection = writingDirection
_containsStart = containsStart
_containsEnd = containsEnd
_isVertical = isVertical
}
}

关于swift - 使用选择矩形(:) with UITextField subclass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58128180/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com