Swift和OC的交互

2020-04-10  本文已影响0人  哥只是个菜鸟

OC调用swift

1.导入头文件

#import "Swift__OC-Swift.h"
image.png

2.需要在swift类的方法前加 “@objc”

@objc public func helloworld(){
        NSLog("hello world", "dhhfdjfh" )
}

3.直接调用

SwiftViewController *vc=[SwiftViewController  new];
    [vc helloworld];

Swift调用OC

1.需要在桥接文件中导入OC类头文件


image.png

2.调用

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let oc = OCViewController()
        self.present(oc, animated: true, completion: nil)
        print(self.login("", pwdlogin: ""))
    }

Block方法

1.声明

//声明
  typealias selectBlock = (_ name:NSString) ->()//block
    var selectblock : selectBlock!

2.调用

  if((selectblock) != nil){
              selectblock("fff")
        }

3.接收回调

 self.selectblock = { (sender) -> Void in
            NSLog("block success %@",sender)  
        }

delegate代理

1.初始化

protocol SelectDelegate {
    func selectbutton(name:NSString);
}

class TableViewCell: UITableViewCell {
    var delegate:SelectDelegate?
}

2.调用

self.delegate?.selectbutton(name: "success")

3.代理方法

func selectbutton(name:NSString) {
        NSLog("delegate %@", name)
    }

添加点击事件

  selectbtn=UIButton.init(frame: CGRect(x: UIScreen.main.bounds.size.width-100, y: 5, width: 80, height: 40))
        selectbtn.setTitle("点击", for:  UIControl.State.normal)
        selectbtn.setTitleColor(UIColor.red, for: UIControl.State.normal)
        selectbtn.addTarget(self, action: Selector(("select")), for: UIControl.Event.touchUpInside)
        self.addSubview(selectbtn)

//
@objc func select() {
}

自定义cell

注册: 
mytableView .register(TableViewCell.self, forCellReuseIdentifier: "cell")

代理方法:
   func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  
      let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for:indexPath) as! TableViewCell
        cell.delegate=self
        return cell
       }

swift报错UICollectionView must be initialized with a non-nil layout parameter

这种写法会报错,为nil

 var collectionview =UICollectionView()

改为这种:

 var mycollectionView : UICollectionView!
上一篇 下一篇

猜你喜欢

热点阅读