从objC访问swift属性
- (void) tapGesture: (id)sender { UITapGestureRecognizer *gesture = (UITapGestureRecognizer *) sender; NSInteger userID = gesture.view.tag; UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; OthersProfile *vc = (OthersProfile*)[storyboard instantiateViewControllerWithIdentifier:@"othersprofile"]; NSString *strUserID = [NSString stringWithFormat:@"%ld", (long)userID]; vc.userID = strUserID; [self.viewController.navigationController pushViewController:vc animated:YES]; }
它曾经与Xcode 8 / Swift 3一起使用,但似乎Xcode 9和swift 4存在问题。
我有属性userID not found错误。
在Swift文件中:
var userID : String = "" override func viewDidLoad() { print(userID) //no value here }
任何有想法的人?
试试这个:
@objc var userID : String = "
在Swift 4中,将Swift代码暴露给Objective-C的规则已经改变 。因此,您的代码在Swift 3中没问题,因此您面临的混乱;)
新设计在相应的Swift Evolution提案中有详细说明。
你需要解决的另一个问题是你如何访问控制器:
这是因为当你尝试设置它时, vc.user
为nil,将一个变量添加到swift控制器并设置它而不是`vc.user.text
vc.yourVariable = strUserID; [self.viewController.navigationController pushViewController:vc animated:YES];
然后在viewDidAppear中,您将能够使用此变量进行设置
@IBOutlet var user: UILabel! public var yourVariable: String = "" override func viewDidLoad() { user.text = yourVariable print(user.text!) //should be value }
- 使用自动布局使宽度和高度相等
- 键盘退出后,使inputAccessoryView可见
- WatchKit reloadRootControllersWithNames导致错误,与pageController或推/popup后
- Swift:将普通string转换为YYYY-MM-DDtypesstring?
- 为什么Bundle.main.path(forResource:fileName,ofType:“txt”)总是返回nil?
- 在SDWebImage代码中解释__weak和__strong的使用原因
- 自定义MKAnnotation标注泡泡
- 如何在Swift中使用NSURLSessionDataTask
- 在创build一系列NSTextContainers时,如何根据文本内容指定容器中断?