0

我创建了一个 Swift 框架,它以编程方式创建一个按钮,按钮的操作显示一个 webView 并关闭它,我的框架在 Swift 项目中工作正常,但在 Objective C 中它只是创建按钮,但它没有采取行动,也没有显示我的 webView,注意:我使用 SwiftyJSON 通过 JSON 从服务器获取按钮配置

下面是框架项目中除了 SwiftyJSON 之外的我的 Swift 类

import Foundation
import UIKit
import WebKit

@objc public class predictionButton : NSObject {
public override init(){

}

var buttonConfigApi = "XXXXXXXXX"
var buttonTextColor = String()
var buttonText = String()
var buttonBackgroundColor = String()
var buttonVisibility = Bool()
var indexURL = String()
var authURL = String()
var module = String()
var buttonAlignment = String()
var globalURL = String()


var webViewX = CGFloat()
var webViewY = CGFloat()
var webViewXiWidth = CGFloat()
var webViewHeight = CGFloat()
  @objc public var globalView = UIView()


var parseFlag = Bool()



var buttonAlignmentValue = String()


@objc public  func addButtonPredict(view: UIView, phone: String, token: String){
    parseJSON()
    sleep(5)

    var phonTok = "{'a':\(phone),'b':\(token)}"

    let utf8str = phonTok.data(using: String.Encoding.utf8)




    let data = (phonTok).data(using: String.Encoding.utf8)
    let base64 = data!.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))



    var finalURL = String()


    self.globalView = view

    finalURL = "\(self.indexURL)?d=\(base64)"
    self.globalURL = finalURL
    let button = UIButton(frame: buttonPosition(view: view, alignValue: buttonAlignment))

    print((self.globalURL))



    button.backgroundColor = hexStringToUIColor(hex: self.buttonBackgroundColor)
    print("global color value \(buttonBackgroundColor)")
    button.setTitle("\(self.buttonText)", for: .normal)

    button.setTitleColor(hexStringToUIColor(hex: self.buttonTextColor), for: .normal)



    let buttonFontSize = 15
    let buttonTitleSize = (buttonText as NSString).size(withAttributes: [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: CGFloat(buttonFontSize + 1))])

    button.frame.size.height = buttonTitleSize.height * 2
    button.frame.size.width = buttonTitleSize.width * 1.5


    view.addSubview(button)
    button.tag = 5
    button.addTarget(self, action: #selector(nest), for: .touchUpInside)



}




@objc func nest (){



    let frame = webViewposition(view: self.globalView)
    let webView = WKWebView(frame: frame)






    webView.load(NSURLRequest(url: NSURL(string: globalURL)! as URL) as URLRequest)
    webView.contentMode = .scaleAspectFit
    webView.tag = 100


    if let viewWithTag = self.globalView.viewWithTag(100) {
        viewWithTag.removeFromSuperview()
    }else{
        print("No!")
        self.globalView.addSubview(webView)
    }
}






@objc public func parseJSON(){

    print("flag")

    let requestURL: NSURL = NSURL(string: buttonConfigApi)!
    let urlRequest: URLRequest = URLRequest(url: requestURL as URL)
    let session = URLSession.shared

    let task = session.dataTask(with: urlRequest as URLRequest) {
        (data, response, error) -> Void in
        if data != nil {



            do
            {

                let readableJSON =  try JSON(data: data!, options: JSONSerialization.ReadingOptions.mutableContainers)
                let Name = readableJSON["data"]["buttonText"].stringValue as String!
                let buttonTextColor = readableJSON["data"]["buttonTextColorCode"].stringValue as String!
                let buttonBackgroundColorCode = readableJSON["data"]["buttonBackgroundColorCode"].stringValue as String!
                let visibility = readableJSON["data"]["visibility"].boolValue
                let indexURL = readableJSON["data"]["indexURL"].stringValue as String!
                let authURL = readableJSON["data"]["authURL"].stringValue as String!
                let module = readableJSON["data"]["module"].stringValue as String!
                let alignment = readableJSON["data"]["alignment"].stringValue as String!

                self.buttonText = Name!
                self.buttonTextColor = buttonTextColor!
                self.buttonBackgroundColor = buttonBackgroundColorCode!
                self.buttonAlignment = self.alignText(text: alignment!)
                self.indexURL = indexURL!
                self.authURL = authURL!
                self.module = module!


                print("\(Name!) \n \(buttonTextColor!) \n \(buttonBackgroundColorCode!) \n  \(indexURL!) \n \(alignment!)")

                print("done")
                print("Color value:\(buttonBackgroundColorCode!)")

            } catch {
                print(error)
            }



        }





    }

    task.resume()

      }

@objc func alignText (text: String) -> String {
    var alignText = String()
    let newString = text.replacingOccurrences(of: "_", with: "", 
  options: .literal, range: nil)

    return newString.lowercased()
}





@objc func hexStringToUIColor (hex:String) -> UIColor {
    var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

    if (cString.hasPrefix("#")) {
        cString.remove(at: cString.startIndex)
    }

    if ((cString.count) != 6) {
        print("became gray")
        return UIColor.gray

    }

    var rgbValue:UInt32 = 0
    Scanner(string: cString).scanHexInt32(&rgbValue)

    return UIColor(
        red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
        green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
        blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
        alpha: CGFloat(1.0)
    )
}


@objc func webViewposition(view: UIView) -> CGRect {

    var frame = CGRect()



    if UIDevice.current.orientation == UIDeviceOrientation.landscapeLeft {
        frame = CGRect(x: (view.frame.width) - (view.frame.width / 4) - 120 , y: 20 , width: view.frame.width / 3 , height: view.frame.height - 60 )



    } else if UIDevice.current.orientation == UIDeviceOrientation.landscapeRight {
        frame = CGRect(x: (view.frame.width) - (view.frame.width / 4) - 120, y: 20 , width: view.frame.width / 3 , height: view.frame.height - 60 )


    } else if UIDevice.current.orientation == UIDeviceOrientation.portrait {
        frame = CGRect(x: 0, y: 110, width: view.frame.width, height: view.frame.height - 60 )


    } else if UIDevice.current.orientation == UIDeviceOrientation.portraitUpsideDown {
        frame = CGRect(x: 0, y: 100, width: view.frame.width, height: view.frame.height - 60 )


    }

    return frame
}



@objc  func buttonPosition(view: UIView, alignValue: String)-> CGRect {
    var position = CGRect()



    switch (alignValue){
    case "lefttop":
        print("button top left")
        position = CGRect(x: 25, y: 50, width: 100, height: 100)



    case "righttop":
        print("button top right")
        position = CGRect(x: view.frame.width - 150, y: 50, width: 100, height: 100)


    case "letbottom":
        print("button bottom left")
        position = CGRect(x: 25, y: view.frame.height - 150, width: 100, height: 100)

    case "rightbottom":
        print("button bottom right")
        position = CGRect(x: view.frame.width - 25, y: view.frame.height - 150, width: 100, height: 100)




    default:
        position = CGRect(x: 25, y: 50, width: 100, height: 100)
    }





    return position
}







  }







  extension UIColor {
       convenience init(red: Int, green: Int, blue: Int) {
    assert(red >= 0 && red <= 255, "Invalid red component")
    assert(green >= 0 && green <= 255, "Invalid green component")
    assert(blue >= 0 && blue <= 255, "Invalid blue component")

    self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 
    255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
     }

convenience init(rgb: Int) {
    self.init(
        red: (rgb >> 16) & 0xFF,
        green: (rgb >> 8) & 0xFF,
        blue: rgb & 0xFF
    )
}
 }

 extension String {
var numberValue:NSNumber? {
    let formatter = NumberFormatter()
    formatter.numberStyle = .decimal
    return formatter.number(from: self)
}
 }

我创建了一个 Objective-C 并在其中添加了构建的框架,它的 .m 文件代码如下:

#import "ViewController.h"
@import myFrameWork;
#import <myFrameWork/myFrameWork-Swift.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];





predictionButton *btn = [[predictionButton alloc] init];


  [btn addButtonPredictWithView:self.view phone:@"XXXXXXX" 
 token:@"XXXXXXXXXXXXXXXXXXXXXXXXXXX"];




 }


  @end

注意:这个框架在 Swift 项目中运行良好

这是工作快速代码:

import UIKit
import myFrameWork
import WebKit

class ViewController: UIViewController {
var button = predictionButton()

override func viewDidLoad() {
    super.viewDidLoad()

    button.addButtonPredict(view: self.view, phone: "XXXXXXXXXX", token: "XXXXXXXXXXXXXXXXXXXXXXXXX")



}
4

0 回答 0