'UIView?' 类型的值没有成员 'titleLabel'

Value of type 'UIView?' has no member 'titleLabel'

我正在尝试为 admob 原生广告 CTA 按钮指定自定义字体。

但是我遇到了这个错误。

Value of type 'UIView?' has no member 'titleLabel'

ListTileNativeAdFactory:

class ListTileNativeAdFactory : FLTNativeAdFactory {

...

...

  (nativeAdView.callToActionView as? UIButton)?.setTitle(nativeAd.callToAction, for: .normal)
  nativeAdView.callToActionView.titleLabel.font = UIFont(name: "Arial", size: 20)//This line gives error! 

...
...

  return nativeAdView

  }

我该如何解决我的问题?谢谢...

您需要重复您在上一行所做的操作:(nativeAdView.callToActionView as? UIButton)?。或者将这两行包装在 if 子句中

if let callToActionButton = nativeAdView.callToActionView as? UIButton {
    callToActionButton.setTitle ...
    ...
}

我解决了我的问题。我们需要 NSAttributedString & NSMutableAttributedString 类.

https://developer.apple.com/documentation/foundation/nsattributedstring

https://developer.apple.com/documentation/foundation/nsmutableattributedstring

对于 nativeAdView,不要使用 setTitle 方法,而是使用

setAttributedTitle 方法。

因此,

解决方法:

class ListTileNativeAdFactory : FLTNativeAdFactory {

...

...

  let myAttribute = [ NSAttributedString.Key.font: UIFont(name: "Arial", size: 20.0)! ]
  let myString = NSMutableAttributedString(string: nativeAd.callToAction!, attributes: myAttribute)
  (nativeAdView.callToActionView as? UIButton)?.setAttributedTitle(myString, for: .normal)

...
...

  return nativeAdView

  }