swift2 将Obj-C转换为Swift

gijlo24d  于 2022-11-06  发布在  Swift
关注(0)|答案(2)|浏览(269)

尝试覆盖Swift2.1中的drawPlaceholderInRect,以便更改文本颜色,但我很难将以下Obj-C转换为Swift:

(void)drawPlaceholderInRect:(CGRect)rect
{
    UIColor *colour = [UIColor whiteColor];

    if ([self.placeholder respondsToSelector:@selector(drawInRect:withAttributes:)]) {

    NSDictionary *attributes = @{NSForegroundColorAttributeName: colour, NSFontAttributeName: self.font};
    CGRect boundingRect = [self.placeholder boundingRectWithSize:rect.size options:0 attributes:attributes context:nil];
    [self.placeholder drawAtPoint:CGPointMake(0, (rect.size.height/2)-boundingRect.size.height/2) withAttributes:attributes];
}

我得到了这个:

public override func drawPlaceholderInRect(rect: CGRect) {
    let textDict: NSDictionary = [NSForegroundColorAttributeName: UIColor.whiteColor()]

    ...
    ..
    .
}

有人能帮帮忙吗?

yhived7q

yhived7q1#

func drawPlaceholder(in rect: CGRect) {

    let colour: UIColor? = UIColor.white

    if placeholder.responds(to: Selector("drawInRect:withAttributes:")) {

        let attributes = [NSForegroundColorAttributeName: colour, NSFontAttributeName: font]

        let boundingRect: CGRect = placeholder.boundingRect(with: rect.size, options: [], attributes: attributes, context: nil)

        placeholder.draw(at: CGPoint(x: 0, y: (rect.size.height / 2) - boundingRect.size.height / 2), withAttributes: attributes)
    }
}
u59ebvdq

u59ebvdq2#

看看这是否有帮助:
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/index.html#//apple_ref/doc/uid/TP40014216-CH2-ID0
此外,如果您在将Objective-C转换为Swift时遇到困难(有时候可能很枣手),请考虑在派生的Objective-C类中覆盖该方法,然后在Swift中使用该类。

相关问题