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

I am trying to specify custom font for admob native ads CTA button.

But I'm getting this error.

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

  }

How can I solve my problem? Thanks...



Solution 1:[1]

I solved my problem. We need NSAttributedString & NSMutableAttributedString classes.

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

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

For nativeAdView, don't use setTitle method, instead use

setAttributedTitle method.

As a result,

The solution:

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

  }

Solution 2:[2]

You'd need to repeat what you did on the line above: (nativeAdView.callToActionView as? UIButton)?. Or wrap these two lines in a if clause

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gurkan stack
Solution 2 PartlyCloudy