将Obj-C转换为Swift

时间:2016-02-08 21:46:30

标签: uitextfield swift2 override

尝试覆盖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()]

    ...
    ..
    .
}

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

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)
    }
}

答案 1 :(得分:0)

看看这是否有用:

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中使用该类。